Friday 16 October 2015

Log4j2: Hello World Application

Create ‘log4j2.xml’ file and place it in your application classpath.
log4j2.xml

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
 <Appenders>
  <Console name="my_console_appender" target="SYSTEM_OUT">
   <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
  </Console>
 </Appenders>
 <Loggers>
  <Root level="info">
   <AppenderRef ref="my_console_appender" />
  </Root>
 </Loggers>
</Configuration>


HelloWorld.java

package log4j_tutorial;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class HelloWorld {
 private static final Logger log = LogManager.getLogger();

 public static void main(String args[]) {
  log.info("Starting application");
  System.out.println("Hello World");
  log.info("Execution completed");
 }
}


Output
12:28:39.378 [main] INFO  log4j_tutorial.HelloWorld - Starting application
Hello World
12:28:39.379 [main] INFO  log4j_tutorial.HelloWorld - Execution completed

LogManager.getLogger()
Returns a Logger with the name of the calling class.

<Loggers>
         <Root level="info">
                  <AppenderRef ref="my_console_appender" />
         </Root>
</Loggers>

‘Loggers’ element defines all the loggers used in your application.  Root logger is created using Root element. You can create custom logger, by using Logger element.

<Logger name="com.foo.Bar" level="trace">
    <AppenderRef ref=" my_console_appender "/>
</Logger>

All the appenders are defined inside Appenders element. Following snippet define Console appender with name my_console_appender, and writes log messages to system console. Log messages are written to appenders by logger, appenders write log messages to external world like console, files, database etc.,

<Appenders>
         <Console name="my_console_appender" target="SYSTEM_OUT">
                  <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
         </Console>
</Appenders>




Prevoius                                                 Next                                                 Home

No comments:

Post a Comment