2

I am trying to do something like the following in the log4j.xml:

<File name="MyFile" fileName="logs/%X{client}]">
    <PatternLayout>
        <Pattern>%d %p %c{1.} [%t] %m%n</Pattern>
    </PatternLayout>
</File>

I have set the key as follows from the java code:

MDC.put( "client", "Roger" );

I have tried ${client} as well inside the log4j2.xml nothing works. How do I refer the MDC key inside the log4j2.xml outside the layout element?

I have also specified a default value for the key under the properties section as follows:

<Properties>
    <Property name="client">default</Property>
</Properties>
StackzOfZtuff
  • 2,534
  • 1
  • 28
  • 25
Shiva
  • 21
  • 3

2 Answers2

0

Instead of the %X pattern converter (which is only for layouts), you want to use a lookup.

In this case, there is a built-in lookup that does what you want: the Context Map Lookup.

Example usage:

<File name="MyFile" fileName="logs/$${ctx:client}]">
StackzOfZtuff
  • 2,534
  • 1
  • 28
  • 25
Remko Popma
  • 35,130
  • 11
  • 92
  • 114
  • 1
    $${ctx:client} does not work. It creates the file as ${ctx – Shiva Jun 29 '17 at 14:49
  • Are you sure that there is a value for that key in the thread context for every thread that does logging? – Remko Popma Jun 29 '17 at 15:12
  • yes it does, but i also tried the default value as in the specified in the question section – Shiva Jun 29 '17 at 15:18
  • You may have found a bug. Would you mind creating a bug report on the Log4j2 JIRA issue tracker? – Remko Popma Jun 30 '17 at 00:47
  • By the way, your question mentions `MDC.put(...`, but the Log4j2 API class is `ThreadContext`. Have you tried using `ThreadContext.put("client", "Roger")` instead? – Remko Popma Jun 30 '17 at 00:50
  • will try that @Remko Popma – Shiva Jun 30 '17 at 19:32
  • log4j2 provides a implementation of slf4j's `MDCAdapter`, which is a wrapper for `ThreadContext` operations. In other words, using `MDC.put(` via slf4j or `ThreadContext.put` via the log4j2 API has the same effect. – Jason Crease May 03 '22 at 13:16
0

You can use Routing RoutingAppender to wrap file appender, and in Routing RoutingAppender can use MDC to separate file.

Find example here: write different logs in different files with log4j2 (MDC)

Reference: RoutingAppender

bluearrow
  • 856
  • 2
  • 11
  • 26