I am trying to write one custom starter in sprintboot for logging. So that all downstream project can follow the same pattern of logging on adding starter in class path.
For this I am trying to create one logback.xml file and using LogstashEncoder. In this project I am using sleuth and zipking also so that I can see the traceId and spanId.
Following is the logback.xml file.
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<include resource="org/springframework/boot/logging/logback/console.xml"/>
<appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>
%d{yyyy-MM-dd HH:mm:ss.SSS} %5p [Orders:%thread:%X{X-B3-TraceId}:%X{X-B3-SpanId}] %logger{40} - %msg%n
</pattern>
</encoder>
</appender>
<appender name="fileout"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<File>c:/elk/orders4.log</File>
<rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
<maxIndex>8</maxIndex>
<FileNamePattern>./logs/orders.log.%i
</FileNamePattern>
</rollingPolicy>e
<triggeringPolicy
class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
<MaxFileSize>128MB</MaxFileSize>
</triggeringPolicy>
<encoder class="net.logstash.logback.encoder.LogstashEncoder">
<customFields>{"tenantId":"log-odyssey"}</customFields>
</encoder>
</appender>
<root level="info">
<appender-ref ref="fileout" />
<appender-ref ref="stdout" />
</root>
</configuration>
Now If you will see in RollingFileAppender I am using one custom field with hardcode value. I want to populate its value dynamically from http request. as tenantId will be resolved from request itself.
Can someone help me to solve this issue how I can populate custom fields value dynamically.
Create a Servlet Filter that retrieves the
tenantIdfrom the request and populates thetenantIdproperty in the logback MDC. LogstashEncoder will automatically include all properties from the MDC in the JSON output for a log event. You don't even need to define a custom field in xml.