你可以使用log4j2 JSONLayout來做到這一點。
例子:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<JSONLayout compact="true" eventEol="true" properties="true"/>
</Console>
</Appenders>
<Loggers>
<Root level="info">
<AppenderRef ref="Console"/>
</Root>
</Loggers>
</Configuration>
在這裏,如果你設置緊湊=假,JSON將打印在prity格式
- 二您可以
ThreadContext
將pu值作爲關鍵值對。
例子:
for (int i = 0; i < 5; i++) {
ThreadContext.clearAll();
ThreadContext.put("delay", String.valueOf(i));
ThreadContext.put("name", "Ash " + i);
LOGGER.info("Testing ", "k1", "v1", "k2", "v2");
}
這裏ThreadContext
把所有的鍵值對,直到你清楚了。
輸出:
{"timeMillis":1491819918389,"thread":"main","level":"INFO","loggerName":"com.ashraful.ilpexp.LogTest","message":"Testing ","endOfBatch":false,"loggerFqcn":"org.apache.logging.log4j.spi.AbstractLogger","contextMap":{"delay":"0","name":"Ash 0"},"threadId":1,"threadPriority":5}
{"timeMillis":1491819918504,"thread":"main","level":"INFO","loggerName":"com.ashraful.ilpexp.LogTest","message":"Testing ","endOfBatch":false,"loggerFqcn":"org.apache.logging.log4j.spi.AbstractLogger","contextMap":{"delay":"1","name":"Ash 1"},"threadId":1,"threadPriority":5}
{"timeMillis":1491819918504,"thread":"main","level":"INFO","loggerName":"com.ashraful.ilpexp.LogTest","message":"Testing ","endOfBatch":false,"loggerFqcn":"org.apache.logging.log4j.spi.AbstractLogger","contextMap":{"delay":"2","name":"Ash 2"},"threadId":1,"threadPriority":5}
{"timeMillis":1491819918505,"thread":"main","level":"INFO","loggerName":"com.ashraful.ilpexp.LogTest","message":"Testing ","endOfBatch":false,"loggerFqcn":"org.apache.logging.log4j.spi.AbstractLogger","contextMap":{"delay":"3","name":"Ash 3"},"threadId":1,"threadPriority":5}
{"timeMillis":1491819918505,"thread":"main","level":"INFO","loggerName":"com.ashraful.ilpexp.LogTest","message":"Testing ","endOfBatch":false,"loggerFqcn":"org.apache.logging.log4j.spi.AbstractLogger","contextMap":{"delay":"4","name":"Ash 4"},"threadId":1,"threadPriority":5}
AFAIK你只能擁有完整的消息作爲一個JSON場。 – Fildor
理想情況下,我想避免這種情況,但要知道沒有辦法也是有幫助的。 – LetsPlayYahtzee
時間戳是消息本身的元信息的一部分,您實際上希望將消息移動到元數據中。你嘗試過MDC嗎? - >如果你使用PatternLayout,你可以把例如上下文中的當前用戶並在消息中重複使用它。如果這不起作用,那麼沒有人會提出解決方案,我會建議實施自己的JsonLayout ... – slowy