![](/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.