问题描述
仅在MDC上设置该值时,如何在log4j条目上打印键/值对?
例如,我目前有以下模式:
%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - client=%X{client} %m%n
我想仅在此密钥上有MDC上的值时才打印"客户端="部分.
例如,启动我的程序时,将没有访问端的登录,因此将使用此模式记录日志:
%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
但是,在客户端登录后(我使用"客户端"键设置MDC之后),我需要使用以下内容进行打印:
%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - client=%X{client} %m%n
log4j上有这样的"条件模式"?
谢谢
推荐答案
我最终使用Xav的建议.
我从log4j模式中删除了" client ="字符串,并每次在MDC上添加条目时都将其附加.这不是最美丽的解决方案,但效果很好!
例如,我否则我会使用
MDC.put("client", client.getId());
我现在正在使用:
MDC.put("client", "client="+client.getId().toString());
其他推荐答案
有一个%notEmpty模式在log4j2中,您可以准确地实现此目的.
%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %notEmpty{client=%X{client} }%m%n
其他推荐答案
a 建议的hack 保持键,因为MDC值有助于将密钥名称绑定到代码中的某些常数.但这对于微服务不利,例如标题对其他服务感到不满,关键名称被重复.
有一个干净的SLF4J 模式 - 逻辑解决方案可以实现这一目标:
%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %replace( client=%mdc{client}){' client=$', ''} %m%n
问题描述
How do I print a key/value pair on a log4j entry only if the value is set on MDC?
For example, I currently have the following pattern:
%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - client=%X{client} %m%n
I'd like to print the "client=" part only if there is a value on MDC for this key.
For example, when starting my program, there will be no client logged in, so logs would be recorded using this pattern:
%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
However, after the client has logged in (and after I have set the MDC with a "client" key), I need to print it using the following:
%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - client=%X{client} %m%n
Is there such "conditional pattern" on log4j?
Thank you
推荐答案
I endend up using xav's suggestion.
I removed the "client=" string from the log4j pattern and appended it everytime I added an entry to MDC. It's not the most beautiful solution but it worked great!
For example, where I otherwise would use
MDC.put("client", client.getId());
I am now using:
MDC.put("client", "client="+client.getId().toString());
其他推荐答案
There is a %notEmpty pattern in Log4j2 which allows you to achieve exactly this.
%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %notEmpty{client=%X{client} }%m%n
其他推荐答案
A suggested hack to keep key with value as MDC value helps to bind key name to some constant in code. But this is not good for microservices when e.g. header is resent to other service and key name gets duplicated.
There is a clean SLF4J pattern-logic solution that allows to achieve this:
%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %replace( client=%mdc{client}){' client=$', ''} %m%n