Suppose we use Logback for logging.
It’s required to change the path to the log file every time a certain event (i.e. function call) occurs.
For example, somewhere we call a function.
startNewLogSegment("A")
After this event, the logger is expected to start writing to the logs/mySegment_A.log
file.
Then, again a call performed:
startNewLogSegment("B")
After this event, the logger is expected to finish writing to the previous file and start writing to the logs/mySegment_B.log
file.
Let's assume that a state changed by startNewLogSegment
should be visible in the whole application (all threads).
I tried to apply the approach with MDC:
logback.xml
...
<appender name="SIFTING_BY_ID" class="ch.qos.logback.classic.sift.SiftingAppender">
<discriminator>
<key>id</key>
<defaultValue>initial</defaultValue>
</discriminator>
<sift>
<appender name="FULL-${id}" class="ch.qos.logback.core.FileAppender">
<file>logs/mySegment_${id}.log</file>
<append>false</append>
<encoder >
<pattern>%d{dd-MM-yyyy HH:mm:ss.SSS} [%thread] [%-5level] %logger{36}.%M - %msg%n</pattern>
</encoder>
</appender>
</sift>
</appender>
...
and calling MDC.put("id", "A")
when a custom event appears.
But it works a different way than I need.
It’s known that the MDC manages contextual information on a per thread basis, so at least we need a control over threads creation to accomplish the goal described above.
I wonder if this approach could be used with Spring, and in particular with async operations performed by Spring Reactor. I’ve found no information about using a custom thread pool for internal Spring activities.
Possibly, I hope, there’s a more simple way to tune logging that way without abusing Spring internals.