Log4j2 ConsoleAppender Example

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

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

1. Log4j2 ConsoleAppender Configuration

Use and customize 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 poperty 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

<?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.1. Using log4j2.properties

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. Confuguring Log4j2

  1. 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.
  2. For standalone java applications, we can use PropertyConfigurator class to configure the logging.
    import org.apache.log4j.Logger;
    import org.apache.log4j.PropertyConfigurator;
     
    public class Demo 
    {
        static Logger logger = Logger.getLogger(Demo.class);
     
        public static void main(String[] args) {
            // PropertiesConfigurator is used to configure logger from a properties file
            PropertyConfigurator.configure("log4j2.xml");
     
            // Log in console
            logger.debug("Log4j console appender configuration is successful !!");
        }
    }
    

3. Demo

We have put the log4j2.xml file in a Spring boot application. We have added the following 3 statements to verify that logs are appearing 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 !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.