import com.foo.Bar;
// Import log4j classes.
import org.apache.log4j.Logger;
import org.apache.log4j.BasicConfigurator;
public class MyApp {
// Define a static logger variable so that it references the
// Logger instance named "MyApp".
static Logger logger = Logger.getLogger(MyApp.class);
public static void main(String[] args) {
// Set up a simple configuration that logs on the console.
BasicConfigurator.configure();
logger.info("Entering application.");
Bar bar = new Bar();
bar.doIt();
logger.info("Exiting application.");
}
}
MyApp begins by importing log4j related classes. It then defines a static logger variable with the name MyApp which happens to be the fully qualified name of the class.
MyApp uses the Bar class defined in the package com.foo.
package com.foo;
import org.apache.log4j.Logger;
public class Bar {
static Logger logger = Logger.getLogger(Bar.class);
public void doIt() {
logger.debug("Did it again!");
}
}
|
The invocation of the BasicConfigurator.configure method creates a rather simple log4j setup. This method is hardwired to add to the root logger a ConsoleAppender. The output will be formatted using a PatternLayout set to the pattern “%-4r [%t] %-5p %c %x – %m%n”.
Note that by default, the root logger is assigned to Level.DEBUG.
The output of MyApp is:
0 [main] INFO MyApp – Entering application. 36 [main] DEBUG com.foo.Bar – Did it again! 51 [main] INFO MyApp – Exiting application.
The figure below depicts the object diagram of MyApp after just having called the BasicConfigurator.configure method.

Link: http://logging.apache.org/log4j/1.2/manual.html
