This article will guide developers on how to integrate methods for getting TraceID and adding TraceID to application logs in the application code, suitable for backend developers with some development experience.
To correctly associate multiple automatically sent spans (different modules/nodes/services called during a single request) into a single trace, the service's HTTP request headers will include TraceID and other information used for associating the trace.
A trace represents the call process of a single request, and TraceID is the unique ID identifying this request. With the TraceID in the logs, the traceing can be associated with the application logs.
Based on the above background, this article will explain how to obtain the TraceID from the HTTP request headers and add it to application logs, allowing you to accurately query log data on the platform using TraceID.
The following examples are based on the Spring Boot framework and use Log4j and Logback for illustration.
Your application must meet the following prerequisites:
The type and version of the logging library must meet the following requirements:
Logging Library | Version Requirement |
---|---|
Log4j 1 | 1.2+ |
Log4j 2 | 2.7+ |
Logback | 1.0+ |
The application has been injected with a Java Agent.
Method 1: Configure logging.pattern.level
Modify the logging.pattern.level
parameter in your application configuration as follows:
Method 2: Configure CONSOLE_LOG_PATTERN
Modify the logback configuration file as follows.
The console output is used as an example here, where %X{trace_id}
indicates the value of the key trace_id
retrieved from MDC.
In the class where logs need to be output, add the @Slf4j
annotation and use the log object to output logs, as shown below:
In the application code, add the following code to retrieve the TraceID from the request headers. The example code is as follows and can be adjusted as needed:
The getForwardHeaders function retrieves trace information from the request headers, where the value of x-b3-traceid
is the TraceID.
In the application code, add the following code to include the retrieved TraceID in the logs. The example code is as follows and can be adjusted as needed:
Click on Tracing in the left navigation bar.
In the query criteria, select TraceID, enter the TraceID to query, and click Add to query.
In the displayed trace data below, click View Log next to the TraceID.
On the Log Query page, check Contain Trace ID; the system will only display log data containing the TraceID.