English 中文(简体)
log4j - Logging Methods
  • 时间:2024-09-17

log4j - Logging Methods


Previous Page Next Page  

Logger class provides a variety of methods to handle logging activities. The Logger class does not allow us to instantiate a new Logger instance but it provides two static methods for obtaining a Logger object −

    pubpc static Logger getRootLogger();

    pubpc static Logger getLogger(String name);

The first of the two methods returns the apppcation instance s root logger and it does not have a name.

Any other named Logger object instance is obtained through the second method by passing the name of the logger. The name of the logger can be any string you can pass, usually a class or a package name as we have used in the last chapter and it is mentioned below −

static Logger log = Logger.getLogger(log4jExample.class.getName());

Logging Methods

Once we obtain an instance of a named logger, we can use several methods of the logger to log messages. The Logger class has the following methods for printing the logging information.

# Methods and Description
1 pubpc void debug(Object message)

It prints messages with the level Level.DEBUG.

2 pubpc void error(Object message)

It prints messages with the level Level.ERROR.

3 pubpc void fatal(Object message)

It prints messages with the level Level.FATAL.

4 pubpc void info(Object message)

It prints messages with the level Level.INFO.

5 pubpc void warn(Object message)

It prints messages with the level Level.WARN.

6 pubpc void trace(Object message)

It prints messages with the level Level.TRACE.

All the levels are defined in the org.apache.log4j.Level class and any of the above mentioned methods can be called as follows −

import org.apache.log4j.Logger;

pubpc class LogClass {
   private static org.apache.log4j.Logger log = Logger.getLogger(LogClass.class);
   
   pubpc 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 compile and run LogClass program, it would generate the following result −

Debug Message!
Info Message!
Warn Message!
Error Message!
Fatal Message!

All the debug messages make more sense when they are used in combination with levels. We will cover levels in the next chapter and then, you would have a good understanding of how to use these methods in combination with different levels of debugging.

Advertisements