javaspring-bootnewrelicspring-logbacknewrelic-platform

How to log MDC context values in New Relic


I am using logback to print the log in my spring boot project. I can see the log printing in the new relic, but it does not print the values from the MDC context.

for example: I have stored x-request-id in the MDC.context and am using the following config file to print the log. I can see the x-request-id printing in the Console and in the log file in the logs/logback-app.log location, but I do not see the x-request-id printing in NewRelic.

I am taking reference from this https://docs.newrelic.com/docs/logs/logs-context/java-configure-logs-context-all/#java-logback documentation. An example from: https://github.com/newrelic/java-log-extensions/blob/main/examples/logback-app/src/main/resources/logback.xml

<configuration>
    <appender name="STDOUT" class="ch.qos.logback.core.FileAppender">
        <file>logs/logback-app.log</file>
        <append>false</append>
        <!-- encoders are assigned the type
             ch.qos.logback.classic.encoder.PatternLayoutEncoder by default -->
        <encoder class="com.newrelic.logging.logback.NewRelicEncoder">
        </encoder>
    </appender>

    <appender name="ASYNC" class="com.newrelic.logging.logback.NewRelicAsyncAppender">
        <appender-ref ref="STDOUT" />
    </appender>
    
    <appender name="Console" class="ch.qos.logback.core.ConsoleAppender">
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <pattern>%X{request-id} %d %-5level [%thread] %logger{0}: %msg%n</pattern>
        </encoder>
    </appender>

    <root level="TRACE">
        <appender-ref ref="ASYNC" />
        <appender-ref ref="Console" />
    </root>
</configuration>

Solution

  • New Relic has provided a flag to forward Diagnostic Context to the new relic agent, we can enable this flag in the newrelic.yml file as follows

    common: &default_settings
        # forwad Diagnostic Context to new relic agent
        forwarding:
            context_data:
                enabled: true