问题
I have this log4j2.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration xmlns="http://logging.apache.org/log4j/2.0/config">
<Appenders>
<File name="FILE" fileName="logfile.log" append="true">
<PatternLayout pattern="%p | [%t] %l | message : %m%n"/>
</File>
<Console name="STDOUT" target="SYSTEM_OUT">
<PatternLayout pattern="%p | [%t] %l | message : %m%n"/>
</Console>
</Appenders>
</Configuration>
And my goal is to add in the RestEndpoint a unique id with uuid, but i dont know how to add to the xml file...or i have to configure it not in an xml file?
回答1:
In your application, put the uuid in the ThreadContext:
ThreadContext.put("myUuid", new UUID());
I assume you know where the entry points in your application are where to put and remove these.
In configuration, extract the UUID from the ThreadContext with the %X
pattern converter: (also added Loggers to your configuration)
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="warn">
<Appenders>
<File name="FILE" fileName="logfile.log" append="true">
<PatternLayout pattern="%p | [%t] %l | id: %X{myUuid} | message : %m%n"/>
</File>
<Console name="STDOUT" target="SYSTEM_OUT">
<PatternLayout pattern="%p | [%t] %l | id: %X{myUuid} | message : %m%n"/>
</Console>
</Appenders>
<Loggers>
<Root level ="trace">
<AppenderRef ref="STDOUT" />
<AppenderRef ref="FILE" />
</Root>
</Loggers>
</Configuration>
回答2:
Feel like there is another solution, which is easier, if what you need is just a unique id for each log record. Check UUID in Log4j doc
The only update is to change the layout in xml file is to add %u{"RANDOM"}
.
sample xml configuration
<PatternLayout>
<pattern>%d{DATE} [%p] UUID:%u{"RANDOM"} (%t) %c: %m%n</pattern>
</PatternLayout>
来源:https://stackoverflow.com/questions/43999342/how-to-add-uuid-to-log4j-for-logging-into-file