在我的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 = |邀请用户的输入数据已经过验证