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.
Business Log Associated with the TraceID
TOC
Background
-
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.
Adding TraceID to Java Application Logs
-
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:
-
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.
TIPThe console output is used as an example here, where
%X{trace_id}indicates the value of the keytrace_idretrieved from MDC. -
In the class where logs need to be output, add the
@Slf4jannotation and use the log object to output logs, as shown below:
Adding TraceID to Python Application Logs
-
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:
TIPThe getForwardHeaders function retrieves trace information from the request headers, where the value of
x-b3-traceidis 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:
Verification Method
-
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.