1

In my spring-boot project, I am trying to implement MDC for logback. In one of my two spring-security filters, I am putting a key-value inside MDC. But in the logs the value inside MDC is not printed.

public class JWTAuthorizationFilter extends BasicAuthenticationFilter {

private static final Logger LOGGER = LoggerFactory.getLogger(JWTAuthorizationFilter.class);

private AuthTokenModelRepository authTokenModelRepository;

public JWTAuthorizationFilter( AuthenticationManager authManager,
        AuthTokenModelRepository authTokenModelRepository )
{
    super(authManager);
    this.authTokenModelRepository = authTokenModelRepository;
}

@Override
protected void doFilterInternal( HttpServletRequest req, HttpServletResponse res, FilterChain chain )
        throws IOException, ServletException
{

    String header = req.getHeader(TokenConstant.HEADER_STRING);

    if( NullEmptyUtils.isNullorEmpty(header) || !header.startsWith(TokenConstant.TOKEN_PREFIX) )
    {
        LOGGER.info("****************JWT not present in the HttpRequest header************************");
        chain.doFilter(req, res);
        return;
    }

    // Check if the user is still active
    Optional<AuthTokenModel> authTokenModelOptional = authTokenModelRepository
            .findByJwtAndIsActiveTrue(header.replace(TokenConstant.TOKEN_PREFIX, ""));
    if( !authTokenModelOptional.isPresent() )
    {
        LOGGER.info("********************User is not logged in*******************************");
        chain.doFilter(req, res);
        return;
    }

    UsernamePasswordAuthenticationToken authentication = getAuthentication(req);

    SecurityContextHolder.getContext().setAuthentication(authentication);

    String userName = (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    MDC.put("user", userName);

    chain.doFilter(req, res);
}

And In my logback.xml, I am defining a pattern, which should append MDC content into the logs.

<property name="LOG_FILE" value="${user.home}/my_logs/logs"/>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
        <level>INFO</level>
    </filter>
    <layout class="ch.qos.logback.classic.PatternLayout">
        <Pattern>
            %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger | refId=%X{user} | %msg%n
        </Pattern>
    </layout>
</appender>

But in the logs present in the console, I am not seeing the MDC contents.

2018-04-28 15:36:15 [http-nio-8090-exec-2] INFO com.highpeak.tlp.webservices.services.impl.InvitationServiceImpl | refId= | Input data to invite user is validated

Naanavanalla
  • 1,412
  • 2
  • 27
  • 52

0 Answers0