Making a log4j console appender use different colors for different threads

匿名 (未验证) 提交于 2019-12-03 08:57:35

问题:

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.

回答1:

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?).

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 - see [1] + "0"        // Brightness + ";"        // Separator + "31"       // Red foreground + "m"        // Suffix + text       // the text to output + "\u001b[m " // Prefix + Suffix to reset color

Here some examples:

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:

                    

[1] What does "\u001B[J" represent?



回答2:

You can use MulticolorLayout from jcabi-log. Add this dependency to the project:

   com.jcabi   jcabi-log   0.17.1 

And then configure it in log4j.properties:

log4j.rootLogger=INFO, CONSOLE log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender log4j.appender.CONSOLE.layout=com.jcabi.log.MulticolorLayout log4j.appender.CONSOLE.layout.ConversionPattern=[%color{%p}] %c: %m%n

Same in log4j.xml:

                         

In this example, %p will be replaced by DEBUG, 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:

log4j.appender.CONSOLE.layout.ConversionPattern=[%p] $color-cyan{%c}: %color-red{%m}%n log4j.appender.CONSOLE.layout.ConversionPattern=[%p] $color-0;0;31{%c}: %m%n

More documentation about ANSI colors.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!