1

In my project I use Log4j 2.17.1. I would like to format the output so that the class names have different colors.

public class MyClass {
    Logger LOGGER = LogManager.getLogger(MyClass.class.getSimpleName());
    
    //...

    LOGGER.debug("Some Information");
}
public class MySecondClass {
    Logger LOGGER = LogManager.getLogger(MySecondClass.class.getSimpleName());

    //...
    
    LOGGER.debug("Another Output");
}

enter image description here

In my example, I want the two classes to appear in different (perhaps random) colors (instead of yellow as in the example).

My current pattern layout:

%highlight{${LOG_LEVEL_PATTERN:-%5p}}{FATAL=red blink, ERROR=red, WARN=yellow bold, INFO=green, DEBUG=green bold, TRACE=blue} : %style{%logger{36}:}{blue} %msg%n

Is this possible with Log4j?

EchtFettigerKeks
  • 1,692
  • 1
  • 18
  • 33
  • It seems random colors per logger aren't supported in log4j. The best option for me is to keep logs plain and give the coloring job to the external viewing tool – Denys Kurochkin Jan 31 '22 at 14:57
  • But you also can try to play with custom Layout implementation - extend the original one which does all the highlighting and wrap it with your specific logic which will understand random colors per logger – Denys Kurochkin Jan 31 '22 at 15:00
  • in the second option, you should take care of color persistence - when you restart application or look at logs from two separate instances - colors should be consistent – Denys Kurochkin Jan 31 '22 at 15:01

1 Answers1

0

Per defeault log4j writes simple text files with no fancy formatting applied (FileAppender, ConsoleAppender).

I have never done this, but I believe you can add ANSI escape sequences using a suitable formatting pattern, then enjoy the colours when the log output is sent to a terminal capable of understanding these sequences.

Queeg
  • 7,748
  • 1
  • 16
  • 42