![](/img/trans.png)
[英]spring boot embedded tomcat append log to every tomcat request
[英]Spring boot with embedded tomcat + access log with authentication user
我正在使用带有嵌入式 tomcat + spring 安全性的 spring 引导。 我来自 tomcat 的访问日志看起来像这样
IP - - [14/Feb/2017:08:49:50 +0200] “GET /page/2 HTTP/1.1”200 2606
那么,我怎样才能使日志文件看起来像
IP - - [14/Feb/2017:08:49:50 +0200]用户名- "GET /page/2 HTTP/1.1" 200 2606
每个请求都必须具有从中发出的用户名。 对于安全身份验证,我使用带有数据库用户名和密码信息的 spring 安全性。
您可能需要将应用程序属性中的访问日志模式更改为如下所示:
server.tomcat.accesslog.pattern=%h %l %t %u "%r" %s %b
其中%u
是已通过身份验证的远程用户(请参阅此处的示例)。
UPD :这可能还不够,因为普通模式已经包含%u
参数。 在这种情况下,我会推荐两个额外的步骤:
request.getSession().setAttribute("username", user.getName());
在访问日志模式中添加以下参数: %{username}s
server.tomcat.accesslog.pattern=%h %l %t %u %{username}s "%r" %s %b
应采取指定属性username
来自HttpSession
,因为它描述了这里。
只是为了添加一个完整的例子来说明我是如何做到这一点的。 由于现有答案没有提供有关如何实现此目标的非常详细的解释。
在您的 spring web 安全配置中键入以下行。
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http
.csrf().disable()
.authorizeRequests()
.anyRequest().authenticated()
.and()
.httpBasic()
.and()
.addFilterAfter(usernameAccessLogFilter(), BasicAuthenticationFilter.class)
.build();
}
@Bean
public UsernameAccessLogFilter usernameAccessLogFilter(){
return new UsernameAccessLogFilter();
}
然后创建一个自定义过滤器:
public class UsernameAccessLogFilter extends GenericFilterBean {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = ((HttpServletRequest) servletRequest);
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if(authentication != null) {
request.getSession().setAttribute("user", authentication.getName());
}
filterChain.doFilter(servletRequest, servletResponse);
}
}
在您的属性文件(.yml 格式)中添加以下内容:
server:
tomcat:
accesslog:
enabled: true
directory: logs
pattern: "%t %a %A %r %s %u %{user}s %B %T %I"
basedir: .
这是我为获得上述结果所要做的一切。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.