Most web applications are hosted behind a load balancer or web-server such as Nginx/HTTPD, which intercepts all the requests and directs dynamic content requests to the application server, such as Tomcat. Correlating requests traversing from the front-end server to the backend servers are general requirements. In this post, we will discuss tracing the request in the simplest way in an Nginx and Spring Boot-based application without using an external heavyweight library like Slueth.
Assign an Identifier to Each Request Coming Into Nginx
Nginx keeps request identifier for HTTP request in a variable $request_id, which is a 32 haxadecimal characters string. $request_idcan be passed to further downstream with request headers. Following configuration passes the $request_id as X-Request-ID HTTP request header to the application server.
Log the Request Identifier in Front-end Access Logs
Include the $request_id in the log format of the Nginx configuration file as follows.
It will print the access logs in the following format:
Intercept the HTTP Request on the Application Server
Every HTTP request coming into the application server will now have the header X-Request-ID, which can be intercepted either in the interceptor or servlet filter. From there, it can be logged along with every log we print in the logs, as follows.
Define a Request Filter Using MDC
Define the following request filter, which reads the request header and puts it in the MDC (read about MDC here). It basically keeps the values in the thread local.
Configure the Logger to Print the Request id
I have used logback, which can read MDC variables in the %X{variable_name} pattern. Update the logback pattern as follows:
It will print the following logs:
This way, you can see the request id in all the logs from the origin to the end. We can configure ELK to aggregate the logs and trace them in a nice user interface to help with troubleshooting.
Get the Generated Request id Back in the Response
Nginx can also add the request id in the response header with the following configuration:
As you see here:
Conclusion
We have explained a simple way to assign a unique identifier to each request, then trace the request end-to-end. You can get more details here.
No comments:
Post a Comment