How to automatically add a username
to each Logback log statement. The username relates to the user principal (identity) making a request to the application. Your application will handle more than one request at a time — if you have more than one user! — so it is important to audit who is doing what.
Specifically, we will learn:
public class UserToMdcFilter implements Filter {
@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
throws IOException, ServletException {
try {
chain.doFilter(request, response);
} finally {
MDC.remove("user");
}
}
@Override
public void destroy() {
// do nothing
}
@Override
public void init(final FilterConfig fc) throws ServletException {
// do nothing
}
}
Positive reference: https://docs.spring.io/spring-security/site/docs/current/reference/html5/#servlet-authentication-securitycontext
doFilter(...)
method above:if ((SecurityContextHolder.getContext() != null)
&& (SecurityContextHolder.getContext().getAuthentication() != null)
&& (SecurityContextHolder.getContext().getAuthentication().getPrincipal() instanceof User)) {
final User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
MDC.put("user", user.getUsername());
}
username
to the MDC using the key user
iff: ## Add The New Filter To The Spring Security Filter Chain Duration: 5
Positive reference: https://docs.spring.io/spring-security/site/docs/current/reference/html5/#servlet-authentication-unpwd
http.addFilterAfter(new UserToMdcFilter(), AnonymousAuthenticationFilter.class);
logback.xml
file.[%X{user:-system}]
user
we placed into the MDC (in the filter) and if none exist use the default string value of system
.%X{user:-system}
into your own layouts): %d{yyyy-MM-dd HH:mm:ss.SSS} %5p ${PID:- } [%X{req.method}][%X{req.requestURL}][%X{user:-system}] [%t] --- %-40.40logger{39} : %m%n%wex