Friday 16 October 2015

Log4j2: levels

LoggerConfigs are associated with a log level; level is used to identify the severity of an event. Following are the built-in log levels supported by log4j2 in ascending order of their priority.

Level
Description
OFF
No events will be logged
TRACE
A fine-grained debug message, typically capturing the flow through the application.
DEBUG
A general debugging event.
INFO
An event for informational purposes.
WARN
An event that might possible lead to an error.
ERROR
An error in the application, possibly recoverable.
FATAL
A severe error that will prevent the application from continuing.

If you set logging level to WARN, then it enables logging for higher levels like WARN, ERROR, FATAL.

log4j2.xml
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="DEBUG">
 <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.trace("Trace Message!");
  log.debug("Debug Message!");
  log.info("Info Message!");
  log.warn("Warn Message!");
  log.error("Error Message!");
  log.fatal("Fatal Message!");
 }
}


When you run above application, you will get following statements in console.

14:33:30.200 [main] INFO  log4j_tutorial.HelloWorld - Info Message!
14:33:30.200 [main] WARN  log4j_tutorial.HelloWorld - Warn Message!
14:33:30.200 [main] ERROR log4j_tutorial.HelloWorld - Error Message!
14:33:30.201 [main] FATAL log4j_tutorial.HelloWorld - Fatal Message!


As you observe the output, trace and debug messages are not printed in console.




Prevoius                                                 Next                                                 Home

No comments:

Post a Comment