Java – Spring Boot – How to log all requests and responses with exceptions in single place

javaloggingspringspring-rest

I'm working on rest api with spring boot. I need to log all requests with input params (with methods, eg. GET, POST, etc), request path, query string, corresponding class method of this request, also response of this action, both success and errors. For example:

successful request:

http://example.com/api/users/1

Log should look something like this:

{
   HttpStatus: 200,
   path: "api/users/1",
   method: "GET",
   clientIp: "0.0.0.0",
   accessToken: "XHGu6as5dajshdgau6i6asdjhgjhg",
   method: "UsersController.getUser",
   arguments: {
     id: 1 
   },
   response: {
      user: {
        id: 1,
        username: "user123",
        email: "user123@example.com"   
      }
   },
   exceptions: []       
}

Or request with error:

http://example.com/api/users/9999

Log should be something like this:

{
   HttpStatus: 404,
   errorCode: 101,                 
   path: "api/users/9999",
   method: "GET",
   clientIp: "0.0.0.0",
   accessToken: "XHGu6as5dajshdgau6i6asdjhgjhg",
   method: "UsersController.getUser",
   arguments: {
     id: 9999 
   },
   returns: {            
   },
   exceptions: [
     {
       exception: "UserNotFoundException",
       message: "User with id 9999 not found",
       exceptionId: "adhaskldjaso98d7324kjh989",
       stacktrace: ...................    
   ]       
}

I want Request/Response to be a single entity, with custom information related to this entity, both in successful and error cases.

What is best practice in spring to achieve this, may be with filters? if yes, can you provide concrete example?

I've played with @ControllerAdvice and @ExceptionHandler, but as I mentioned, I need to handle all success and error requests in single place (and single log).

Best Answer

Don't write any Interceptors, Filters, Components, Aspects, etc., this is a very common problem and has been solved many times over.

Spring Boot has a modules called Actuator, which provides HTTP request logging out of the box. There's an endpoint mapped to /trace (SB1.x) or /actuator/httptrace (SB2.0+) which will show you last 100 HTTP requests. You can customize it to log each request, or write to a DB.

To get the endpoints you want, you'll need the spring-boot-starter-actuator dependency, and also to "whitelist" the endpoints you're looking for, and possibly setup or disable security for it.

Also, where will this application run? Will you be using a PaaS? Hosting providers, Heroku for example, provide request logging as part of their service and you don't need to do any coding whatsoever then.