Before we really start on this, you have to remember only one thing: you have to log everything! Every request. I don’t care if it’s a GET, a POST, a PUT, if it had success, if returned some kind of validation error, I really don’t care. Log everything.
You only log the errors? Sorry, you are doing it wrong! How do you know when a specific user made a request? How are you going to create that wonderful dashboards full of statistics with tools like Kibana or Grafana? And of course, another thing that is great for those dashboards is to log the log level itself. Actually, it should be mandatory to record if that log entry is an INFO, WARN, ERROR, etc.
Typically, a backend application serves an API (it could be B2B, B2C, but that doesn’t matter). What’s important is that you want to know which service the user just called, so you have to log the name of the endpoint. And even though that name is quite specific, it’s always a good idea to log also the type of HTTP method of the endpoint. What changed? Was a resource created? Was a resource retrieved? How many? Do you see what I mean? This is the data that will become invaluable at some point in your project. And typically, it’s information that you have at the moment of the response, so you don’t have any excuse not to log it!
Bonus points: thread/request id. It’s always nice to have this when you have to track a long operation that logs a lot of details: like queries or even custom information, which is being recorded at the same time that the application is still receiving other requests. The multiple lines of logging different requests can get mixed up and it can become a real mess to find anything. The identifier of a request can prevent a situation like this, or it can be easily resolved with a simple search.
- 2019–04–06 17:02:30.414 INFO [req-000000086] [c.b.a.controller.ApiController] [operationName=ApiController.getAll, httpMethod=GET, IPAddress=100.200.300.400, userId=55df8919, executionTime=12, size=5] [operationResult=OK]
- 2019–04–06 12:10:21.741 INFO [req-000000052] [c.b.a.controller.ApiController] [operationName=ApiController.get, httpMethod=GET, IPAddress=100.200.300.400, userId=55df8919, executionTime=5, resourceId=1000] [operationResult=OK]