1

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?

Michael Petch
  • 46,082
  • 8
  • 107
  • 198
  • 1
    have a look at this question: http://stackoverflow.com/questions/23325389/spring-boot-enable-http-requests-logging -- is this what you want? – Ralph Dec 12 '16 at 12:32
  • This could be it, but are some other options to do this? –  Dec 12 '16 at 12:46
  • How could i post this with form [[${#httpServletRequest.remoteUser}]] tried th:value=*{[[${#httpServletRequest.remoteUser}]]} –  Dec 12 '16 at 13:14

1 Answers1

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 the HttpServletResponse so that it returns your writer rather than the default one (for more info look at this question)
Community
  • 1
  • 1
g00glen00b
  • 41,995
  • 13
  • 95
  • 133