49

Hi I just downloaded and configured log4j-2. I am stuck on applying color codes to the SlowConsole console appender. My console appender is like below.

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{HH:mm:ss.SSS} %-5level %logger{36} - %msg%n"/>
        </Console>
        <Console name="SlowConsole" target="SYSTEM_OUT">
            <PatternLayout pattern="%highlight{%d{HH:mm:ss.SSS} %-5level %logger{36}.%M() @%L - %msg%n}{FATAL=red, ERROR=red, WARN=yellow, INFO=black, DEBUG=green, TRACE=blue}"/>
        </Console>
        <File name="File" fileName="C:\log\out.txt">
            <PatternLayout pattern="%d{HH:mm:ss.SSS} %-5level %logger{36} - %msg%n" />
        </File>
    </Appenders>
    <Loggers>
        <logger name="org.abc.ea.web" level="ALL" additivity="false">
            <!--Log4j for the WEB MODULE -->
            <appender-ref ref="SlowConsole"/>
        </logger>
        <logger name="org.abc.ea.ejb" level="ALL" additivity="false">
            <!--Log4j for the EJB MODULE -->
            <appender-ref ref="SlowConsole"/>
        </logger>
        <Root level="ERROR">
            <AppenderRef ref="Console"/>
            <AppenderRef ref="File" />
        </Root>
    </Loggers>
</Configuration>

I have two questions,

  1. I am new to log4j, is this the right way to write xml config file?

  2. How can i add two color codes to each log level?

    for example: DEBUG=green -> will output light green font, But i need it to be dim and bold

Govinnage Rasika Perera
  • 2,134
  • 1
  • 21
  • 33

8 Answers8

67

I think I found the solution. I downloaded log4j2-core-sources.jar and traced the source. You can write it as below;

<Console name="SlowConsole" target="SYSTEM_OUT">
     <PatternLayout disableAnsi="false"  pattern="%highlight{%d{HH:mm:ss.SSS} %-5level %logger{36}.%M() @%L - %msg%n}{FATAL=red blink, ERROR=red, WARN=yellow bold, INFO=black, DEBUG=green bold, TRACE=blue}"/>
</Console>

I think log4j2 documentation and its examples may need to be updated.

Kalpesh Soni
  • 6,879
  • 2
  • 56
  • 59
Govinnage Rasika Perera
  • 2,134
  • 1
  • 21
  • 33
47

For a log4j2 colored output that looks very close to Spring Boot's default logback console output:

    <Console name="ConsoleAppender" target="SYSTEM_OUT" follow="true">
        <PatternLayout pattern="%d{${LOG_DATEFORMAT_PATTERN:-yyyy-MM-dd HH:mm:ss.SSS}} %highlight{${LOG_LEVEL_PATTERN:-%5p}}{FATAL=red blink, ERROR=red, WARN=yellow bold, INFO=green, DEBUG=green bold, TRACE=blue} %style{${sys:PID}}{magenta} [%15.15t] %style{%-40.40C{1.}}{cyan} : %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}"/>
    </Console>

Console Screenshot

Berthier Lemieux
  • 3,785
  • 1
  • 25
  • 25
  • 1
    Exactly what I wanted after applying custom log config! – Frankie Drake May 07 '18 at 14:35
  • 2
    I get _Unrecognized conversion specifier [wEx] starting at position 209 in conversion pattern._ anyone know what is going on? – ycomp Jan 26 '19 at 07:23
  • Yes it's looks like original Logback Spring logger. Exactly what I looked for. But it doesn't work without disableAnsi="false" attribute in PatternLayout tag. Thank you! – Rustam Shafigullin Jul 04 '20 at 17:54
  • 8
    @ycomp I've modified pattern and the issue that you've mentioned is also resolved... Try following pattern: `` – BlueDev Jul 28 '20 at 17:31
8

When using the eclipse console, its nice to see errors in red and all other logs in black. You can do this using Filters:

<Appenders>
    <Console name="ConsoleStdOut" target="SYSTEM_OUT">
        <ThresholdFilter level="ERROR" onMatch="DENY" onMismatch="ACCEPT"/>
        <PatternLayout pattern="%d{HH:mm:ss} [%t] %-5level %logger{36} - %msg%n" />
    </Console>
    <Console name="ConsoleStdErr" target="SYSTEM_ERR">
        <ThresholdFilter level="ERROR" onMatch="ACCEPT" onMismatch="DENY"/>
        <PatternLayout pattern="%d{HH:mm:ss} [%t] %-5level %logger{36} - %msg%n" />
    </Console>
</Appenders>
<Loggers>
    <Root level="info">
        <AppenderRef ref="ConsoleStdOut" />
        <AppenderRef ref="ConsoleStdErr" />
    </Root>
</Loggers>
B_St
  • 180
  • 2
  • 9
5
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT" follow="true">
            <PatternLayout
                    pattern="%clr{%d{yyyy-MM-dd HH:mm:ss.SSS}}{faint} %clr{%5p} %clr{${sys:PID}}{magenta} %clr{---}{faint} %clr{[%15.15t]}{faint} %clr{%-40.40c{1.}}{cyan} %clr{:}{faint} %m%n%xwEx"/>
        </Console>
    </Appenders>
    <Loggers>
        <Root level="info">
            <AppenderRef ref="Console"/>
        </Root>
    </Loggers>
</Configuration>

This worked in my Spring Boot application.

But I am not sure if it will work without Spring Boot.

BaiJiFeiLong
  • 3,716
  • 1
  • 30
  • 28
5

Spring Boot style:

<Properties>
  <Property name="LOG_PATTERN">
    %d{yyyy-MM-dd HH:mm:ss.SSS} %highlight{${LOG_LEVEL_PATTERN:-%5p}}{FATAL=red, ERROR=red, WARN=yellow, INFO=green, DEBUG=green, TRACE=green} %style{${sys:PID}}{magenta} --- [%15.15t] %style{%-40.40c{1.}}{cyan} : %m%n%ex
  </Property>
</Properties>

<Appenders>
  <Console name="Console" target="SYSTEM_OUT">
    <PatternLayout pattern="${LOG_PATTERN}"/>
  </Console>
</Appenders>
yuen26
  • 871
  • 11
  • 12
3

If anyone is looking to achieve the same with log4j2.properties file. Works for log4j2 2.17.1 and above versions

status = warn

# Name of the configuration
name = ConsoleAndRollingLogFileAppenderConfigDemo

# Console appender configuration
appender.console.type = Console
appender.console.name = consoleLogger
appender.console.layout.type = PatternLayout
appender.console.layout.disableAnsi=false
appender.console.layout.pattern = %d{yyyy-MM-dd HH:mm:ss.SSS} %highlight{${LOG_LEVEL_PATTERN:-%5p}}{FATAL=red, ERROR=red, WARN=yellow, INFO=green, DEBUG=green, TRACE=green} %style{%pid}{magenta} --- [%15.15t] %style{%-40.40c{1.}}{cyan} : %m%n%ex

# Log files location
property.basePath = src/main/resources

# RollingFileAppender name, pattern, path and rollover policy
appender.rolling.type = RollingFile
appender.rolling.name = fileLogger
appender.rolling.fileName= ${basePath}/app.log
appender.rolling.filePattern= ${basePath}/app_%d{yyyyMMdd}.log.gz
appender.rolling.layout.type = PatternLayout
appender.rolling.layout.pattern = %d{yyyy-MM-dd HH:mm:ss.SSS} %highlight{${LOG_LEVEL_PATTERN:-%5p}}{FATAL=red, ERROR=red, WARN=yellow, INFO=green, DEBUG=green, TRACE=green} %style{%pid}{magenta} --- [%15.15t] %style{%-40.40c{1.}}{cyan} : %m%n%ex
appender.rolling.policies.type = Policies

# RollingFileAppender rotation policy
appender.rolling.policies.size.type = SizeBasedTriggeringPolicy
appender.rolling.policies.size.size = 100MB
appender.rolling.policies.time.type = TimeBasedTriggeringPolicy
appender.rolling.policies.time.interval = 30
appender.rolling.policies.time.modulate = true
appender.rolling.strategy.type = DefaultRolloverStrategy
appender.rolling.strategy.delete.type = Delete
appender.rolling.strategy.delete.basePath = ${basePath}
appender.rolling.strategy.delete.maxDepth = 10
appender.rolling.strategy.delete.ifLastModified.type = IfLastModified

# Delete all files older than 30 days
appender.rolling.strategy.delete.ifLastModified.age = 60d

# Root logger level
rootLogger.level = debug

# Configure root logger
rootLogger.appenderRef.stdout.ref = consoleLogger
rootLogger.appenderRef.rolling.ref = fileLogger
1

1 : yes it's ok! and you can add some other options. see http://logging.apache.org/log4j/2.x/manual/configuration.html

2 : you can use a HTMLLayout for your file appender.

see http://logging.apache.org/log4j/2.x/manual/layouts.html

and http://www.tutorialspoint.com/log4j/log4j_htmllayout.htm

Farvardin
  • 5,336
  • 5
  • 33
  • 54
  • Thanks @Homayoun! My second question is not yet been solved. I am using a consoleAppender. I want my logs to be viewed on netbeans, eclipse or any STD_OUT. So HTMLLayout wont work, isnt it? – Govinnage Rasika Perera Feb 24 '14 at 12:38
  • it depends on your stdout viewer... for example eclipse stdout (output) has not any sense about bold for example. – Farvardin Feb 24 '14 at 12:49
1

In log4j2 2.18.0 significant improvements were added in highlighting and generated ANSI code:

  • 4 bit color support was added. Before 2.18.0 it was possible to use WARN=bright blue but generated ANSI code anyway used only 3 bit color palette and set font weight as bold. Now it is possible to use all 16 colors and besides to change font weight. For this purpose it is necessary to use bright_ prefix. For example WARN=bright_blue or with font weight WARN=bright_blue bold. For details see this issue

  • true color support was added. For example, WARN=#00ff00. At the same time it is possible to change both foreground and background color. For details see this issue. For example:

    %highlight{%d [%t] %-5level: %msg%n%throwable}{FATAL=white, ERROR=red, WARN=bg_#5792e6 fg_#eef26b bold, INFO=black, DEBUG=#3fe0a8, TRACE=blue}
    
Pavel_K
  • 10,748
  • 13
  • 73
  • 186