Run Trivial.java Example in log4j-1.2.17.zip

Q

How to run the Trivial.java example program in log4j-1.2.17.zip? I have log4j-1.2.17.zip installed at \local\apache-log4j-1.2.17 folder.

✍: FYIcenter.com

A

Trivial.java is an example program provided in the log4j-1.2.17.zip. It is used to show you how to use Log4j with the default configuration. Here is the source code of Trivial.java in the \local\apache-log4j-1.2.17\examples folder:

/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
   ...
 */
package examples;
import org.apache.log4j.Logger;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.NDC;
// ...
public class Trivial {

  static Logger logger = Logger.getLogger(Trivial.class);

  public static void main(String[] args) {
    BasicConfigurator.configure();
    NDC.push("Client #45890"); 

    logger.info("Awake awake. Put on thy strength.");
    Trivial.foo();
    InnerTrivial.foo();
    logger.info("Exiting Trivial.");    
  }

  static
  void foo() {
    NDC.push("DB"); 
    logger.debug("Now king David was old.");    
    NDC.pop(); 
  }

  static class InnerTrivial {
    static  Logger logger = Logger.getLogger(InnerTrivial.class);

    static    
    void foo() {
      logger.info("Entered foo."); 
    }
  }
}

You can follow these steps to run the Trivial.java example program:

\fyicenter>cd \local\apache-log4j-1.2.17

\lccal\apache-log4j-1.2.17>java -version
java version "1.7.0_45"

\local\apache-log4j-1.2.17>javac -cp log4j-1.2.17.jar examples\Trivial.java

\local\apache-log4j-1.2.17>java -cp .;log4j-1.2.17.jar examples.Trivial

0 [main] INFO examples.Trivial Client #45890 - Awake awake. Put on thy strength.
0 [main] DEBUG examples.Trivial Client #45890 DB - Now king David was old.
1 [main] INFO examples.Trivial$InnerTrivial Client #45890 - Entered foo.
1 [main] INFO examples.Trivial Client #45890 - Exiting Trivial.

The source code and the output shows that

  • Logger.getLogger(Trivial.class) is used to create a logger object with the class name.
  • BasicConfigurator.configure() is used to set the logger to use the default configuration.
  • NDC.push() and NDC.pop() are used to manage the context identification.
  • logger.info("Exiting Trivial.") is used to log a message at the "INFO" level.
  • "0 [main] INFO ..." in the log output gives the execution time, thread name, log level and other log information.

Back to FAQ for Log4j - A Logging Library for Java.

2016-06-27, 1054👍, 0💬