Making a log4j console appender use different colors for different threads(使 log4j 控制台附加程序为不同的线程使用不同的颜色)
问题描述
我正在追踪一些并发问题,当登录到控制台时,让每个线程的输出行以不同的颜色显示会非常有帮助.我在 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 实现.- 使用 Log4J 进行颜色编码的控制台日志记录 博文.
补充一下,也许你也可以通过在 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 控制台附加程序为不同的线程使用不同的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使 log4j 控制台附加程序为不同的线程使用不同的
基础教程推荐
- Java Swing计时器未清除 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 大摇大摆的枚举 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 多个组件的复杂布局 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 从 python 访问 JVM 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
