Log4j2 ConsoleAppender Example

Log4j2 ConsoleAppender appends the log events generated by the application into the System.out or System.err. The default target is System.err.

The console appender uses the log message pattern specified by the user in configuration using PatternLayout property.

1. Log4j2 ConsoleAppender Configuration

Use and customize the below-given configuration snippets for configuring the console appender. Notice the followings:

  • We can define the common log pattern LOG_PATTERN constant in Properties sections and reuse it with multiple appenders.
  • The target property specifies the target of the logging messages i.e. SYSTEM_OUT or SYSTEM_ERR.
  • The follow attribute tells whether the appender should honor the reassignments of System.out or System.err made after the logging configuration has been initialized.

1.1. Using log4j2.xml

In the following configuration, we are configuring the ‘console’ appender with specified LOG_PATTERN whose target is SYSTEM_OUT.

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN" monitorInterval="30">
    <Properties>
        <Property name="LOG_PATTERN">%d{yyyy-MM-dd'T'HH:mm:ss.SSSZ} %p %m%n</Property>
    </Properties>
 
    <Appenders>
        <Console name="console" target="SYSTEM_OUT" follow="true">
            <PatternLayout pattern="${LOG_PATTERN}"/>
        </Console>
    </Appenders>
 
    <Loggers>
        <Root level="info">
            <AppenderRef ref="console"/>
        </Root>
    </Loggers>
</Configuration>

1.2. Using log4j2.properties

In the following configuration, we are configuring ‘console’ appended with the specified conversionPattern whose target is System.out.

log4j.rootCategory=info,console
 
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.target=System.out
log4j.appender.console.immediateFlush=true
log4j.appender.console.encoding=UTF-8
#log4j.appender.console.threshold=info
   
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.conversionPattern=%d{yyyy-MM-dd'T'HH:mm:ss.SSSZ} %p %m%n

2. Initialization

Most web frameworks (e.g. Spring boot) will not need any specific code to bootstrap the logging configuration. All we need to do is to put the log4j2.xml or log4j2.properties file in the classpath.

For standalone Java applications, we can use Configurator class to configure the logging. This is especially useful when we are configuring Log4j2 for specific unit tests.

Configurator.initialize("TestClass", "log4j2.xml");

Note that log4j2.xml or the specified file must be present in the application’s classpath.

3. Demo with Spring Boot

We have put the log4j2.xml file in a Spring boot application. We have added the following 3 statements to verify that logs appear in the console and with the correct threshold.

In the above config file, we have set threshold value to info, so only info and error logs will be printed in the console.

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.ApplicationContext;
 
@SpringBootApplication
public class Application extends SpringBootServletInitializer {
 
  private static final Logger LOGGER = LoggerFactory.getLogger(Application.class);
 
  public static void main(String[] args) {
    ApplicationContext ctx = SpringApplication.run(Application.class, args);
 
    LOGGER.info("Info level log message");
    LOGGER.debug("Debug level log message");
    LOGGER.error("Error Message Logged !!!", new NullPointerException("NullError"));
  }
}

Console output:

2021-02-24T18:24:00.107+0530 INFO Info level log message
2021-02-24T18:24:00.109+0530 ERROR Error Message Logged !!!
java.lang.NullPointerException: NullError
  at com.howtodoinjava.logging.demo.Application.main(Application.java:20) [classes/:?]

Happy Learning !!

Comments

Subscribe
Notify of
guest
2 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode