log4j 打印线程号配置,在日志中显示线程ID而不是线程名称

I have a Struts application with log4j to display information about application.

The pattern to format log's output is as follows:

log4j.appender.RALL.layout.ConversionPattern=[%p] %d{dd/MM/yyyy HH:mm:ss} [THREAD ID=%t] [CLASS=(%C{1}:%L)] %m%n

I need to show the thread id instead the thread name in log. The conversion character that display the thread name is %t. I don't see in log4j documentation the way to get it.

Can anyone help me??

解决方案

It is possible but not so easy as just using some preconfigured patterns.

Log4j 1.X and Log4j 2.x don't have any preconfigured patterns for printing Thread ID but you can always use some "magic trick".

PatternLayout is using PatternParser class which is mark as final class and has static map of "patterns" as keys and Converters classes as values. Everytime when Parses finds pattern using for logging pattern format starting with % it uses converter matched with this pattern key in map.

You cannot add your own rule to that map, but you can still write your own MyOwnPatternLayout:

public class MyOwnPatternLayout extends PatternLayout

which will in it's format method do such trick:

public String format(LoggingEvent event) {

String log = super.format(event);

/*

Now you just have to replace with regex all occurences of %i or

any mark you would like to use as mark to represent Thread ID

with Thread ID value.

Only thing you have to be sure to not use any mark as your Thread ID

that already is defined by PatterParser class

*/

return log.replaceAll("%i", someThreadID);

}

The only problem is that you have to get that thread ID in some way. Sometimes all you have to do is to parse Thread name witch can you easly collect:

String threadName = event.getThreadName();

For example Apache-Tomcat put thread ID at the end of thread name http-nio-/127.0.0.1-8084"-exec-41.

To be sure that thread ID is correct you can also make your own subclass of LogginEvent and Logger (MyLoggingEvent and MyLogger) and inside MyLogger create MyLoggingEvent witch will also take as argument Thread ID not only Thread Name. Then you can easly collect it in code above.

Sorry for long answer and I hope this will at least give you some help.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值