ए भाई Think ज़रा हटके
Note: amtyThumb must be installed for new version of amty thumb post/recent

How to use Log4j – An efficient and sufficient guide with examples

Logging, in short, is required to track programming flow. It is very difficult to track code flow or to find faults in Big applications. Log4j makes it easier.

Log4j is usually configured using a property file or XML file externally. You can easily control its behavior through configuration file without modifying the source code.

Prerequisite

  1. What is log4j and why to use it – A short review
  2. Download and import log4j.jar to your project.

Main components

  1. Logger – used to log messages
  2. Appender – specifies the output destination like console or a file (default ConsoleAppender)
  3. Layout – specify the format in which the log messages should be logged (default PatternLayout)

In short to remember

  1. Logger – Who writes to log (Worker)
  2. Appender – Tells where to write (Navigator)
  3. Layout – format the log message (Designer)

Sample configuration file


log4j.rootLogger=WARN, CA
log4j.appender.CA=org.apache.log4j.ConsoleAppender
log4j.appender.CA.layout=org.apache.log4j.PatternLayout
log4j.appender.CA.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n<span style="font-size: 10pt; font-family: "Courier New";">
</span></pre>
<pre>

Explanation -1st line in above configuration line is used to declare logger (who will write). 2nd line is declaring appender (Where he will write). 3rd & 4th line are saying in what format logger will write.

Please note this

You can define any number of loggers per your need. Every logger will have an appender and a pattern layout. You can specify more setting that we learn in further session.

LevelMany times we need to write error log in a separate log file while debug logs in separate log files. Log4j ease to write logs in separate log files for a same logger based on their levels.

The log4j levels follow the following order.

  • DEBUG
  • INFO
  • WARN
  • ERROR
  • FATAL

In the above sample configuration file, logger level is set to WARN. It means, all log message up to WARN level (WARN, ERROR and FATAL) will be written to console (since appender type is ConsoleAppender). Rest logs would be dropped.

Writing to a single log file might not be a good idea. It makes the file longer. You should use multiple logger and multiple levels as per your application nature. For example, separate logs for

  • Errors
  • Client IP tracke
  • Login, Logout time
  • etc.

How to write logs

Once you have done all settings in configuration file ie log4j.properties, place it on the root of your project folder. Your application will pick it automatically. Now

  1. You just need to create an object of logger class in your application.
    public static Logger as_looger = Logger.getLogger("CA");
  2. And write log statement as we write System.out.println(). You can pass Exception object. It automatically prints stack trace.
    as_logger.debug(“article-stack.com has been started.”);

Sample Application

  1. Create a java project
  2. Create a class, say basic.java
    package com.articlestack.log4j;
    import org.apache.log4j.Logger;
    /**
     * This class fetch log settings from log4j.properties
     * @author amty
     */
    public class basic {
    	static final Logger logger = Logger.getLogger("CA");
    	public static void main(String[] args) {
    		logger.debug("Sample debug message");
    		logger.info("Sample info message");
    		logger.warn("Sample warn message");
    		logger.error("Sample error message");
    		logger.fatal("Sample fatal message");
    	}
    }
    
  3. Create log4j.properties. And place it to root of your project folder (refer above screen shot)
    log4j.rootLogger=WARN, CA
    log4j.appender.CA=org.apache.log4j.ConsoleAppender
    log4j.appender.CA.layout=org.apache.log4j.PatternLayout
    #log4j.appender.CA.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
    #log4j.appender.CA.layout.ConversionPattern=%5r %-5p [%t] %c{2} - %m%n
    log4j.appender.CA.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %c{1} [%p] %m%n
    

    *Change the level WARN to DEBUG or to ERROR or something else. Run the application. And check what you get on console.

Some Alternates

  1. My own property file
    Don’t you wanna refer log4j.properties? You can create your own property file similar to log4j.properties. Now place it somewhere. And configure its path through code.

    PropertyConfigurator.configure("amtyLog.properties");
  2. Complete class

    package com.articlestack.log4j;
    
    import org.apache.log4j.Logger;
    import org.apache.log4j.PropertyConfigurator;
    
    public class anotherFile {
    
    	static final Logger logger = Logger.getLogger("AC");
    	public static void main(String[] args) {
    		PropertyConfigurator.configure("amtyLog.properties");
    		logger.debug("Sample debug message"); 
    		logger.info("Sample info message"); 
    		logger.warn("Sample warn message"); 
    		logger.error("Sample error message"); 
    		logger.fatal("Sample fatal message");
    
    	}
    }
    
  3. No property file
    Don’t you wanna refer any property file?You can create a log class. You can do all settings from java code instead property file. Refer the below class.

    package com.articlestack.cofig;
    
    import org.apache.log4j.ConsoleAppender;
    import org.apache.log4j.Level;
    import org.apache.log4j.Logger;
    import org.apache.log4j.PatternLayout;
    
    public class Log
    {
         public static Logger as_looger;
        public Log(){}
        static
        {
            as_looger = Logger.getLogger("articles logging");
            ConsoleAppender as_appender = new ConsoleAppender(new PatternLayout("%d{dd-MM-yyyy HH:mm:ss} %C %L %-5p: %m%n"));
            as_looger.setLevel(Level.DEBUG);
            as_looger.addAppender(as_appender);
        }
    }
    
    

    Now you can log from any java class very easily

    Log.as_looger.debug("DEBUG");
    
    Please note this

    You can skip reading this. This is just an Appendix.

    The org.apache.log4j.Level class provides following levels but you can also define your custom levels by sub-classing the Level class.

    Level Description
    ALL All levels including custom levels.
    DEBUG Designates fine-grained informational events that are most useful to debug an application.
    ERROR Designates error events that might still allow the application to continue running.
    FATAL Designates very severe error events that will presumably lead the application to abort.
    INFO Designates informational messages that highlight the progress of the application at coarse-grained level.
    OFF The highest possible rank and is intended to turn off logging.
    TRACE Designates finer-grained informational events than the DEBUG.
    WARN Designates potentially harmful situations.

    *Above levels are alphabetically short not by priority.

    I had tried to cover all basic concepts of log4j in this article. Tell me if something is not clear to your or missing. Now the time is to use the power of log4j. That we’ll discuss in next article.

    Amit Gupta

    Hey! this is Amit Gupta (amty). By profession, I am a Software Eng. And teaching is my passion. Sometimes I am a teacher, as you can see many technical tutorials on my site, sometimes I am a poet, And sometime just a friend of friends...

5752
views


To book below area mail me




  • Nice tips. In my opinion using correct logging level for different message is most important thing to learn and logging has important performance impact (ever found process running in DEBUG mode in production ) and has to be handled efficiently. I have also blogged my tips as my favorite java logging tips , let me know how do you find it.

  • @JP, its good that you find this post useful. But I never visited your site before as you stated in your last sentence.

  • Hey Amit,
    nice article…can you please help me in finding how could i make use of log4j to write the log files to hadoop

  • I never worked on Hadoop. But I googled “hadoop log4j” and found some good stuff. Read this from their official http://wiki.apache.org/hadoop/HowToConfigure

    I hope it’ll help you

captcha

You can follow any responses to this entry through the RSS 2.0 feed.