How to conditionally add text from MDC on a LOG4J pattern?

拟墨画扇 提交于 2019-12-06 20:55:29

问题


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


回答1:


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



回答2:


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());


来源:https://stackoverflow.com/questions/24616745/how-to-conditionally-add-text-from-mdc-on-a-log4j-pattern

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!