MDC不将用户名记录到日志中

时间:2018-04-28 10:06:59

标签: spring-boot spring-security mdc

在我的spring-boot项目中,我正在尝试为MDC实施logback。 在我的两个spring-security filters中的一个中,我将一个键值放在MDC中。但是在日志中,不会打印MDC内的值。

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);
}

在我的logback.xml中,我正在定义一个模式,该模式应将MDC内容附加到日志中。

<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>

但是在控制台中的日志中,我没有看到MDC内容。

  

2018-04-28 15:36:15 [http-nio-8090-exec-2] INFO com.highpeak.tlp.webservices.services.impl.InvitationServiceImpl | refId = |邀请用户的输入数据已经过验证

0 个答案:

没有答案