我正在尝试通过Logback在我的Spring4应用程序中记录某些事件。 从logback文档中获取,我具有以下UserId筛选器
@Component
public class UserIdFilter implements Filter {
public static final String USERID = "userid";
@Override
public void init(FilterConfig filterConfig) throws ServletException {}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
String userName = AccessLogger.getUserName();
MDC.put(USERID, userName);
try {
filterChain.doFilter(servletRequest, servletResponse);
} finally {
MDC.remove(USERID);
}
}
@Override
public void destroy() {}
}
它会根据请求将MDC中的用户名设置为“ userid”,并将用户名正确添加到日志输出中(该日志已发送到ELK堆栈中)
<appender name="LOGSTASH" class="ch.qos.logback.classic.sift.SiftingAppender">
<filter class="de.app.log.PackageFilter">
<level>de.app</level>
</filter>
<discriminator>
<key>userid</key>
<defaultValue>unknown</defaultValue>
</discriminator>
<sift>
<appender name="LOGSTASH-SIFT" class="net.logstash.logback.appender.LogstashTcpSocketAppender">
<destination>elk:5000</destination>
<encoder class="net.logstash.logback.encoder.LoggingEventCompositeJsonEncoder">
<providers>
...
<mdc/>
<logstashMarkers/>
</providers>
</encoder>
</appender>
</sift>
</appender>
我还试图登录成功的登录名,其中尚未在UserIdFilter中设置“ userid”,但此后用户将通过一个成功处理程序(在WebSecurityConfigurerAdapter中配置):
public class SimpleAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
private static final Logger LOG = LoggerFactory.getLogger(SimpleAuthenticationSuccessHandler.class);
@Override
public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
User user = (User) authentication.getPrincipal();
String username = user.getUsername();
MDC.put(UserIdFilter.USERID, username);
LOG.info(LogEvent.LOGIN, user.toString());
MDC.remove(UserIdFilter.USERID);
redirectStrategy.sendRedirect(httpServletRequest, httpServletResponse, "/");
}
}
但是,AuthenticationSuccessHandler似乎遇到了某种并发性问题,在该问题中,它采用来自其他用户的MDC变量作为日志输出。结果是,某些登录事件从已经登录的用户获取用户ID。在随后再次通过UserIdFilter设置MDC的日志事件中,似乎是正确的:
June 19th 2018, 15:14:35.602 | User: johndoe | event: submit | message: ChangeRequest submitted
June 19th 2018, 15:14:16.364 | User: johndoe | event: modified | message: Form modified
June 19th 2018, 15:06:47.567 | User: chris | event: login | message: de.app.User@5aa59640: Username: johndoe
June 19th 2018, 14:36:27.221 | User: chris | event: login | message: de.app.User@e7b516eb: Username: chris
->第三行:用户 johndoe 通过MDC将 chris 作为登录事件的userId
有人知道如何或在何处正确实施/配置吗?
答案 0 :(得分:0)
以上解决方案有效!
我们已经在SuccessHandler中使用LogStashMarker而不是MDC进行了尝试,由于分支,MDC-Solution未正确发布到生产中,而Markers导致了不良行为。这也解释了为什么我们无法在开发中重新创建行为……du!
很抱歉占用您的时间,但也许上面的代码对某人有帮助。