Logger class has methods to handle logging activities. We can create instance of the Logger class with two static methods:
public static Logger getRootLogger(); public static Logger getLogger(String name);
The first method returns the root logger without a name. The second method returns a logger by name. The name of the logger can be any string. We normally use the class or package name as follows:
static Logger log = Logger.getLogger(log4jExample.class.getName());
We can use the following methods from the Logger class to log messages.
Methods | Description |
---|---|
public void debug(Object message) | prints messages with the level Level.DEBUG. |
public void error(Object message) | prints messages with the level Level.ERROR. |
public void fatal(Object message) | prints messages with the level Level.FATAL. |
public void info(Object message) | prints messages with the level Level.INFO. |
public void warn(Object message) | prints messages with the level Level.WARN. |
public void trace(Object message) | prints messages with the level Level.TRACE |
All the levels are defined in the org.apache.log4j.Level class.
import org.apache.log4j.Logger; public class Main { private static org.apache.log4j.Logger log = Logger.getLogger(Main.class); 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!"); } }