我正在追踪一些并发问题,当登录到控制台时,让每个线程的输出行以不同的颜色显示会非常有帮助.我在 OS X 上.这可以使用转换模式来输出一些控制代码还是需要自定义附加程序来完成?有人知道怎么做吗?
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
并覆盖 format(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 转义序列.
In order to output color to the console, you'll need to use an ANSI Escape Sequence.
例如,输出红色文本:
"u001b[" // Prefix - see [1]
+ "0" // Brightness
+ ";" // Separator
+ "31" // Red foreground
+ "m" // Suffix
+ text // the text to output
+ "u001b[m " // Prefix + Suffix to reset color
这里有一些例子:
ColoredPatternLayout
由 Ingo Thon 实现.补充一下,也许你也可以通过在 MDC 中设置一个带有随机 ANSI 颜色代码的变量randColor"来实现这一点,例如,在 Filter
中,并在 Filter
中使用它log4j 的控制台附加程序配置中标准 org.apache.log4j.PatternLayout
的 code>conversionPattern:
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>
[1] 什么是u001B[J"代表?
这篇关于使 log4j 控制台附加程序为不同的线程使用不同的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!