使log4j控制台附加器为不同的线程使用不同的颜色 [英] Making a log4j console appender use different colors for different threads
问题描述
我正在跟踪一些并发问题,这将是非常有帮助的输出线从每个线程在不同的颜色,当日志到控制台。我在OS X。这可以使用转换模式来输出一些控制代码,还是需要一个自定义appender?任何人都知道如何?
I am tracking down some concurrency issues and it would be very helpful to have the output lines from each thread in a different color when logging to a console. I am on OS X. Could this be done using a conversion pattern to output some control codes or would it need a custom appender? Anyone know how?
2011-10-21 12:14:42,859 ["http-bio-8080"-exec-9] DEBUG ...
2011-10-21 12:14:43,198 ["http-bio-8080"-exec-10] DEBUG ...
exec-9和exec-10的行应该有不同的颜色。
The lines for exec-9 and exec-10 should be in different colors.
推荐答案
您可以扩展 PatternLayout
并覆写 格式(ILoggingEvent)
。您可以查看 LoggingEvent.getThreadName()
来获取基于线程名称的一些颜色(奇数/偶数,也许?)。
You can extend PatternLayout
and override format(ILoggingEvent)
. There you could look at LoggingEvent.getThreadName()
to get some color based on the thread name (odd/even, maybe?).
为了向控制台输出颜色,您需要使用 ANSI Escape Sequence 。
In order to output color to the console, you'll need to use an ANSI Escape Sequence.
例如,要输出红色文本:
For instance, to output a red text:
"\u001b[" // Prefix
+ "0" // Brightness
+ ";" // Separator
+ "31" // Red foreground
+ "m" // Suffix
+ text // the text to output
+ "\u001b[m " // Prefix + Suffix to reset color
这里有一些例子:
-
ColoredPatternLayout
由Ingo Thon执行。 - 使用Log4J的颜色编码控制台记录博客帖子。
ColoredPatternLayout
implementation by Ingo Thon.- Colour-coded Console Logging with Log4J blog post.
只是为了添加,也许你也可以实现这通过在MDC中设置具有随机ANSI颜色代码的变量randColor,例如在 Filter
中,并且在 conversionPattern在您的log4j的控制台附加程序配置中的标准
: org.apache.log4j.PatternLayout
的
Just to add, maybe you could also achieve this by setting in the MDC a variable "randColor" with a random ANSI color code, for instance, in a Filter
, and using it in the conversionPattern
of a standard org.apache.log4j.PatternLayout
in your log4j's console appender configuration:
<appender name="consoleAppender" class="org.apache.log4j.ConsoleAppender">
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern"
value="\u001b[0;%X{randColor}m ....... \u001b[m" />
</layout>
</appender>
这篇关于使log4j控制台附加器为不同的线程使用不同的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!