使 log4j 控制台附加程序对不同线程使用不同颜色
我正在追踪一些并发问题,当登录到控制台时,让每个线程的输出行以不同的颜色显示将非常有帮助。我使用的是 OS X。可以使用转换模式来输出一些控制代码来完成此操作,还是需要自定义附加程序?有人知道怎么做吗?
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 的行应该采用不同的颜色。
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 ...
The lines for exec-9 and exec-10 should be in different colors.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用
MulticolorLayout
来自 jcabi-log。将此依赖项添加到项目中:然后在
log4j.properties
中进行配置:log4j.xml
中相同:在本例中,
%p
将替换为DEBUG、INFO、ERROR等,然后涂成与日志记录级别相关的颜色。除此之外,您还可以使用自己的颜色或预定义的颜色,例如:有关 ANSI 颜色。
You can use
MulticolorLayout
from jcabi-log. Add this dependency to the project:And then configure it in
log4j.properties
:Same in
log4j.xml
:In this example,
%p
will be replaced byDEBUG
,INFO
,ERROR
, etc. and then painted into the color that is relevant to the logging level. Besides that you are able to use your own colors or predefined colors, for example:More documentation about ANSI colors.
您可以扩展
PatternLayout
并覆盖格式(ILoggingEvent)
。在那里你可以查看LoggingEvent.getThreadName()
根据线程名称获取一些颜色(也许是奇数/偶数?)。为了将颜色输出到控制台,您需要使用 ANSI 转义序列。
例如,要输出红色文本:
这里有一些示例:
ColoredPatternLayout
由 Ingo Thon 实施。只是补充一下,也许您还可以通过在 MDC 中设置具有随机 ANSI 颜色代码的变量“randColor”来实现此目的,例如在
Filter
中,并在conversionPattern 中使用它log4j 控制台附加程序配置中标准 org.apache.log4j.PatternLayout 的
:[1] “\u001B[J”代表什么?
You can extend
PatternLayout
and overrideformat(ILoggingEvent)
. There you could look atLoggingEvent.getThreadName()
to get some color based on the thread name (odd/even, maybe?).In order to output color to the console, you'll need to use an ANSI Escape Sequence.
For instance, to output a red text:
Here some examples:
ColoredPatternLayout
implementation by Ingo Thon.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 theconversionPattern
of a standardorg.apache.log4j.PatternLayout
in your log4j's console appender configuration:[1] What does "\u001B[J" represent?
请参阅 PatternLayout,配置属性“highlight”:https://logging。 apache.org/log4j/2.x/manual/layouts.html#PatternLayout
See PatternLayout, configuration property "highlight": https://logging.apache.org/log4j/2.x/manual/layouts.html#PatternLayout