Log4j Logging Levels
log4j
logging
levels
When it came to levels of logging always is in some way confusing. This article will try to add some light on the topic.
These are the levels used by log4j.
ALL | The ALL has the lowest possible rank and is intended to turn on all logging. |
DEBUG | The DEBUG Level designates fine-grained informational events that are most useful to debug an application. |
ERROR | The ERROR level designates error events that might still allow the application to continue running. |
FATAL | The FATAL level designates very severe error events that will presumably lead the application to abort. |
INFO | The INFO level designates informational messages that highlight the progress of the application at coarse-grained level. |
OFF | The OFF has the highest possible rank and is intended to turn off logging. |
TRACE | The TRACE Level designates finer-grained informational events than the DEBUG |
WARN | The WARN level designates potentially harmful situations. |
How is it working?
The main rule of log4j is: A log request of level x in a logger of level y is logged only if level x >= y.
For the standard levels, this is the order: ALL <TRACE < DEBUG < INFO < WARN < ERROR < FATAL < OFF.
Example
The example is using Log4j 1.2.17.
package com.admfactory.log;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
public class Log4jLevelsExample {
private static org.apache.log4j.Logger log = Logger.getLogger(Log4jLevelsExample.class);
public static void main(String[] args) {
log.setLevel(Level.WARN);
log.trace("Trace Message!");
log.debug("Debug Message!");
log.info("Info Message!");
log.warn("Warn Message!");
log.error("Error Message!");
log.fatal("Fatal Message!");
}
}
Setting
The log4j.properties file used in this example:
# Root logger option
log4j.rootLogger=INFO, stdout
# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=[%d{yyyy-MM-dd HH:mm:ss}] [%-5p] %c{1}:%L - %m%n
Note: for maven users the log4j.properties file need to be located in /src/main/resources folder.
Output
[2017-02-08 18:02:35] [WARN ] Log4jLevelsExample:16 - Warn Message!
[2017-02-08 18:02:35] [ERROR] Log4jLevelsExample:17 - Error Message!
[2017-02-08 18:02:35] [FATAL] Log4jLevelsExample:18 - Fatal Message!
As you can see the output respect the order and will print only WARN,ERROR and FATAL.