用Thymeleaf在Spring Boot中记录活动的最佳方法是什么? [英] What is the best way to log Activity in Spring Boot with Thymeleaf?
问题描述
我想记录用户在我的Web服务上发出的请求.用户登录后,用户可以针对服务器api发出请求.我想记录哪个用户发出了哪个请求,输入和输出是什么,等等.
I want to log requests made by users on my webservice. User logs in then user can do requests against servers api. I want to log which user made which request, what was the input and output so on.
让我们说用户通过将新对象提交到将要更新的服务器来编辑某些内容,我想知道是谁做的,以前是什么.
Lets say user edits something, by submitting new object to server which will be updated, i want to know who did that, what was it before.
这是我目前使用的方法,但是效果不是很好.
This is what i use at the moment, but it is not very effective.
logging.level.org.thymeleaf=DEBUG
logging.level.org.springframework.boot=TRACE
我的一个主意是添加method(....,String Username),这样我就可以记录所有内容.这是一个好主意,还是有更好的方法呢?
One idea i have is to add method(...., String Username) so i could log everything. Is this a solid idea, or there is better way to do this?
推荐答案
您可以通过启用以下属性来使用普通访问日志记录(Tomcat):
You can either go with the normal access logging (Tomcat) by enabling this property:
server.tomcat.access-log-enabled=true
这允许您记录您还可以编写自己的过滤器,例如:
You can also write your own filter, for example:
@Component
@Ordered(Ordered.LOWEST_PRECEDENCE)
public class LogFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
// Log the info you need
// ...
filterChain.doFilter(request, response);
}
}
如果确保在Spring Security过滤器链之后执行此过滤器,则可以访问users主体.您还具有HttpServletRequest
和HttpServletResponse
对象,这将允许您同时记录请求正文和响应正文,尽管我认为这将是非常昂贵的操作.
If you make sure that this filter is executed after the Spring Security filter chain, you have access to the users principal. You also have the HttpServletRequest
and HttpServletResponse
objects, which will allow you to log both the request body and the response body, though I think that would be a very expensive operation.
- 可以使用
request.getServletPath()
记录路径
- 可以使用多种方式登录用户名,例如
SecurityContextHolder.getContext().getAuthentication().getName()
.只需通过更改顺序来确保您的安全筛选器已执行(有关更多信息,请参见此问题) - 可以通过获取
request.getReader()
并将其记录下来来记录请求正文(有关更多信息,请参见此问题 ) - 也可以通过创建自己的
Writer
包装器并覆盖HttpServletResponse
来检索响应主体,以便它返回您的编写器而不是默认的编写器(有关更多信息,请参见
- The path can be logged with
request.getServletPath()
- The username can be logged in various ways, such as
SecurityContextHolder.getContext().getAuthentication().getName()
. Just make sure that your security filter has been executed already by changing the order (for more info look at this question) - The request body can be logged by getting the
request.getReader()
and log it (for more info look at this question) - The response body can be retrieves as well by creating your own
Writer
wrapper and overriding theHttpServletResponse
so that it returns your writer rather than the default one (for more info look at this question)
这篇关于用Thymeleaf在Spring Boot中记录活动的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!