12

I'm currently working on a Java project and we are using logging. When a Log is made it is always printed in plain black text, whatever the logging level (INFO, ERROR, etc.)

How can I override the colour of these outputs so for example all ERROR logs will be red while all WARN logs will be orange etc.

Thanks

EDIT: I managed to download the ANSIColorLayout file and my log4j.properties now refers to it. However I get the following errors:

log4j:WARN No such property [all] in org.apache.log4j.ConsoleAppender.
log4j:WARN No such property [reset] in org.apache.log4j.ConsoleAppender.
log4j:WARN No such property [stacktrace] in org.apache.log4j.ConsoleAppender.
log4j:WARN No such property [info] in org.apache.log4j.ConsoleAppender.
log4j:WARN No such property [error] in org.apache.log4j.ConsoleAppender.
log4j:WARN No such property [defaultcolor] in org.apache.log4j.ConsoleAppender.

My log4j.properties file looks like this:

log4j.rootLogger = DEBUG, CA, FA

log4j.appender.CA = org.apache.log4j.ConsoleAppender
log4j.appender.CA.layout = balle.logging.ANSIColorLayout
log4j.appender.CA.layout.ConversionPattern=%-5p [%d{MM-dd-yyyy HH:mm:ss}] %c - %m%n
log4j.appender.CA.all=\u001B[1;37m log4j.appender.A1.fatal=\u001B[1;31m
log4j.appender.CA.error=\u001B[0;31m log4j.appender.A1.warn=\u001B[1;33m
log4j.appender.CA.info=\u001B[0;37m log4j.appender.A1.debug=\u001B[0;36m
log4j.appender.CA.reset=\u001B[1;37m
log4j.appender.CA.stacktrace=\u001B[0;31m
log4j.appender.CA.defaultcolor=\u001B[1;37m

My guess is that I'm supposed to use my own custom ConsoleAppender? Does anyone have any ideas?

Thanks

Dan_Dan_Man
  • 504
  • 2
  • 6
  • 19

1 Answers1

8

You can download one of the various ANSIColorLayout.java implementation. These "color loggers" work by extending the PatternLayout class.

Then you can simply do something like this in your log4j properties:

log4j.appender.stdout.layout=com.acme.ANSIColorLayout

Here's a link to one ANSIColorLayout.java ready to use:

http://code.google.com/p/a-distributed-file-system/source/browse/trunk/DistributedFileSystem/ui/net/dfs/ui/ANSIColorLayout.java

Abdul Alim Shakir
  • 1,128
  • 13
  • 26
TacticalCoder
  • 6,275
  • 3
  • 31
  • 39
  • Should the link be broken you can Google on *"ANSIColorLayout extends PatternLayout"* and you'll find other links : ) – TacticalCoder Feb 20 '12 at 19:49
  • This may seem like a dumb question but how do I edit the log4j conf to use the Color Class? I'm not sure I have it? – Dan_Dan_Man Feb 22 '12 at 15:20
  • @Dan_Dan_Man: it depends on the type of log4j conf file you're using. I did add the line that allows to change the *stdout* output to use the color logger. – TacticalCoder Feb 22 '12 at 15:30
  • I mean for each Class we use logging we import org.apache.log4j.Logger. After that we create a LOG variable and use that to print out different log messages. So do we add that line to each class where we use logging? – Dan_Dan_Man Feb 22 '12 at 15:49