Sunday, February 9, 2014
Log4j is a simple, reliable, fast and extensible open source logging and tracing API. Logging is an important part of any software development lifecycle and is the only way to debug in certain production systems where it is not feasible to use debuggers.

To use these examples download Log4j from https://logging.apache.org/log4j/1.2/.

Let us quickly start with something minimal and the then try to understand Log4j terminology and APIs.

Using Log4J BasicConfigurator to log debug messages to the console

In this example we create a static logger instance and initialize using a basic configurator which logs all debug messages to the console.

package com.sourcetricks.log4j;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;

public class Log4jTest {
  // Initialize logger for instance Log4jTest
  static Logger log  = Logger.getLogger(Log4jTest.class);
    
  public static void main (String[] args) {
    // Basic configurator to log debug messages to the console
    BasicConfigurator.configure();         
          
    // Add some log messages
    log.debug("This is a debug message");
    log.trace("This is a trace message");         
  }
}

Output
0 [main] DEBUG com.sourcetricks.log4j.Log4jTest  - This is a debug message

Using Log4J BasicConfigurator to log all messages to the console

In this example we set the log level to log all messages to the console. Only difference from the previous example is that we have set the log level to log all messages to the console. Please note that in the output we get both the log messages unlike the previous example.

package com.sourcetricks.log4j;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;

public class Log4jTest {
  // Initialize logger for instance Log4jTest
  static Logger log  = Logger.getLogger(Log4jTest.class);
    
  public static void main (String[] args) {
    // Set the level to log all messages
    log.setLevel(Level.ALL);

    // Basic configurator to log all messages to the console
    BasicConfigurator.configure();         
          
    // Add some log messages
    log.debug("This is a debug message");
    log.trace("This is a trace message");         
  }
}

Output
0 [main] DEBUG com.sourcetricks.log4j.Log4jTest  - This is a debug message
2 [main] TRACE com.sourcetricks.log4j.Log4jTest  - This is a trace message

With this basic examples let us jump into some terminology to understand Log4j better.

Log4J Terminology

Logger Hierarchy

In Log4j the loggers follow a hierarchy. There is always a root logger accessed using Logger.getRootLogger() and all other loggers are instantiated and accessed using Logger.getLogger(). Logger instances follow a named hierarchy. For example, com.sourcetricks is considered parent of com.sourcetricks.log4jtest.

Log Levels

Loggers can be assigned various levels including OFF, TRACE, DEBUG, INFO, WARN, ERROR, FATAL and ALL. By default if a logger is not assigned a level it inherits the level from the first non null level from the logger hierarchy towards the root logger.

Appenders

Appenders define the output destination for logs. Examples include console, file, syslog etc. Appenders also follow the logger hierarchy.

Layouts

Log4j allows the log output line to be customized as well. This is called layouts.
e.g) 0 [main] DEBUG com.sourcetricks.log4j.Log4jTest  - This is a debug message

Configuration

Log4j provides the capability and flexibility to fully customize the logging needs either via APIs, Java properties (key = value) format or using XML files. Normal convention to use configuration files instead of APIs to perform the Log4j customization.

With this basic introduction let us look at some more examples to understand better the various customization options.

Using Log4J PropertyConfigurator to log debug messages to the console

In this example we use a PropertyConfigurator and specify the properties file to log debug messages to the console. Additionally we use the layout customization.

package com.sourcetricks.log4j;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

public class Log4jTest {

    // Initialize logger for instance Log4jTest
    static Logger log  = Logger.getLogger(Log4jTest.class);
	
    public static void main (String[] args) {	
	// Property configurator
	PropertyConfigurator.configure("resources/log4j.console");		
		
	// Add some log messages
	log.debug("This is a debug message");
	log.trace("This is a trace message");
    }
}

Properties file
# Set root logger
log4j.rootLogger=DEBUG, console
 
# Add log messages to console
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.Target=System.out
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c - %m%n

Output
2014-02-09 07:58:03 DEBUG com.sourcetricks.log4j.Log4jTest - This is a debug message

With this basic understanding now it is all about customizing the property files to meet our customization needs. Please refer to this article Log4j properties configuration examples on some sample Log4J property file examples.

28 comments :

  1. Your technical information related with java programming is very useful and interesting. Also share updated details about java in your website. Thanks for sharing this article.

    ReplyDelete

  2. Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging…
    Regards,
    ccna training in Chennai

    ReplyDelete
  3. Learning new technolgoy would help oneself at hard part of their career. And staying updated is the only way to survive in current position. Your content tells the same. Thanks for sharing this information in here. Keep blogging like this.

    JAVA J2EE Training Institutes in Chennai

    ReplyDelete
  4. Very happy to see this blog. Gives a wonderful information with coded explanaion. Thank you for this blog. very useful to me.
    Java Training in Chennai

    ReplyDelete
  5. I am following your blog from the beginning, it was so distinct & I had a chance to collect conglomeration of information that helps me a lot to improvise myself. I hope this will help many readers who are in need of this vital piece of information. Thanks for sharing & keep your blog updated.
    Regards,
    CCNA Training in Chennai | CCNA Training institute in Chennai | CCNA Training

    ReplyDelete
  6. What a great post with website design and development services along with wp-plugins, Android IOS, Android Applications Development, SMS Marketing Applications, Conference Calling Apps, API'S Development, Plugins Contact Us

    ReplyDelete
  7. Nice topic you have discussed. Keep sharing !

    PPC training in chennai

    ReplyDelete
  8. Wonderful post. Thanks for sharing such a useful post.

    seo training in chennai

    ReplyDelete

  9. Good Post! Thank you so much for sharing this pretty post.
    qtp Training in Chennai

    ReplyDelete
  10. This comment has been removed by the author.

    ReplyDelete
  11. his was actually what i was looking for, and i am glad to came here! Thank you very much
    eklablog
    Uporabnik
    productzone
    over-blog
    doodlekit
    blog

    ReplyDelete
  12. Well Said, you have furnished the right information that will be useful to anyone at all time. Thanks for sharing your Ideas.
    Web Designing Course in Chennai | web designing training in chennai

    ReplyDelete
  13. Thanks for sharing this unique and informative content which provided me the required information.
    Java Training in Chennai | JAVA Course in Chennai

    ReplyDelete

Contact Form

Name

Email *

Message *

Back to Top