问题
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
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?
回答1:
You can either go with the normal access logging (Tomcat) by enabling this property:
server.tomcat.access-log-enabled=true
This allows you to log anything specified in the AccessLogValve docs.
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);
}
}
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.
- 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)
来源:https://stackoverflow.com/questions/41100999/what-is-the-best-way-to-log-activity-in-spring-boot-with-thymeleaf