TIP

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

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

TIP
  • 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 LibraryVersion Requirement
      Log4j 11.2+
      Log4j 22.7+
      Logback1.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:

logging.pattern.level = trace_id=%mdc{trace_id}

Method 2: Configure CONSOLE_LOG_PATTERN

  1. Modify the logback configuration file as follows.

    TIP

    The console output is used as an example here, where %X{trace_id} indicates the value of the key trace_id retrieved from MDC.

    <property name="CONSOLE_LOG_PATTERN"
        value="${CONSOLE_LOG_PATTERN:-%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} [trace_id=%X{trace_id}] %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}"/>
    
  2. In the class where logs need to be output, add the @Slf4j annotation and use the log object to output logs, as shown below:

    @RestController
    @Slf4j
    public class ProviderController {
    
        @GetMapping("/hello")
        public String hello(HttpServletRequest request) {
            log.info("request /hello");
            return "hello world";
        }
    }
    

Adding TraceID to Python Application Logs

  1. 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:

    TIP

    The getForwardHeaders function retrieves trace information from the request headers, where the value of x-b3-traceid is the TraceID.

       def getForwardHeaders(request):
           headers = {}
           incoming_headers = [
               'x-request-id',  # All applications should pass x-request-id for access logs and consistent tracing/log sampling decisions
               'x-b3-traceid',  # B3 trace header, compatible with Zipkin, OpenCensusAgent, and Stackdriver configurations
               'x-b3-spanid',
               'x-b3-parentspanid',
               'x-b3-sampled',
               'x-b3-flags',
           ]
           for ihdr in incoming_headers:
               val = request.headers.get(ihdr)
               if val is not None:
                   headers[ihdr] = val
    
           return headers
    
  2. 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:

    headers = getForwardHeaders(request) tracing_section = ' [%(x-b3-traceid)s,%(x-b3-spanid)s] ' % headers logging.info(tracing_section + "Oops, unexpected error happens.")

Verification Method

  1. Click on Tracing in the left navigation bar.

  2. In the query criteria, select TraceID, enter the TraceID to query, and click Add to query.

  3. In the displayed trace data below, click View Log next to the TraceID.

  4. On the Log Query page, check Contain Trace ID; the system will only display log data containing the TraceID.