Logging with log4j Example :Java


Logging is a very important part of programming that provides advanced debugging capabilities and structured organisation of information recorded at the run time. If I say debugging, you may ask "Why not System.out.println (SOP)?". SOP is a powerful debugging technique that helps to troubleshoot all the errors at the time of development. But when you implement your application in a real time environment, unexpected results and exceptions might occur. Logging provides you an effective mechanism to track all the errors that occurs in your application after you deploy it, so that you can understand what went wrong with your application.

Log4j is an effective open source Logging API that is written in Java by the Apache Software Foundation. All logging API's share a common architecture that consists of three main components,

log4j_architecture
log4j Components
1. Loggers: Loggers are responsible for capturing logging information
2. Appenders: Through appenders you tell the system on where to log the information such as files, database.etc.
3. Layouts: Layouts enable you to specify the format or displaying style of logging information.

In this post, I am going to provide step by step instructions for implementing logging with log4j in a simple Java Application using Eclipse IDE with appropriate code and screenshots.

1. First of all download the latest version of log4j and unzip it.Locate  log4j-xxx.jar file where xxx denotes the version of log4j release you have downloaded.

2. Open Eclipse IDE and create a Java Project and name it. In this example I have named it as "LoggingExample".



3. Create a package under the default package, by right clicking on 'src' in Package Explorer > New > Package, I have named this package as 'test'.


4. Next step is to add the log4j-xxx.jar you have downloaded to the application you have just created. To do this, right click on the project in Package Explorer > Build Path > Configure Build Path


In the Java Build Path dialogue, go to Library tab, Click Add External JARs and add the log4j-xxx.jar > Click OK.


Now the log4j jar file is available to be used in your application.

5. Now create a file named as "log4j.properties" in your default package where all your source code is placed. This is the file that is going to hold all the configuration settings for log4j implementation for all classes in your application. To do this, right click the default package, in this case 'src' in package explorer > New > File >File Name: log4j.properties


6. Copy the below code to the log4j.properties file you just created

# Log levels
log4j.rootLogger=INFO,CONSOLE,R
# Appender Configuration
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
# Pattern to output the caller's file name and line number
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n
# Rolling File Appender
log4j.appender.R=org.apache.log4j.RollingFileAppender
# Path and file name to store the log file
log4j.appender.R.File=./logs/testlog.log
log4j.appender.R.MaxFileSize=200KB
# Number of backup files
log4j.appender.R.MaxBackupIndex=2
# Layout for Rolling File Appender
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%d - %c - %p - %m%n

Explanation to the above configuration file

First step is to define the log level. Log4j logs messages at six different levels. For example, if you have a program that generates lot of warning messages then you can ignore them by setting the log level to ERROR to avoid the log file getting more clumsy. The log levels and the priority is as follows,

TRACE < DEBUG < INFO < WARN < ERROR < FATAL

If you specify the log level as WARN, then the INFO, DEBUG and TRACE log level messages will be omitted while the WARN, ERROR and FATAL log level messages will be logged. In our example we have set the log level as INFO which means TRACE level logs will not be logged.


Next comes the appender settings. I have used two appenders, Console Appender and Rolling file appender. This means my log information will be displayed on the console as well as stored in a file. Since we have used RollingFileAppender, log4j will open a new file whenever the log file reaches the maximum file size of 200 KB mentioned in R.MaxFileSize property and the old one will be backed up. You can specify the number of backup files in the R.MaxBackupIndex property.


log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender log4j.appender.R=org.apache.log4j.RollingFileAppender

You can also use other appenders, like JDBCAppender,SocketAppender,SysLogAppender etc. according to your requirement to route the logging information to appropriate destinations.



Each appender is associated with layout settings that specifies the format of information that is being logged. I have used PatternLayout for both the appenders and have defined two different patterns for each of them. For console appender,


log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n

where,
%5p - Priority of the logging event
%t - Name of the thread that initiated the logging event
%F- File name where the logging issue was requested
%L - line number that caused the logging message to be generated

Sample output of the above layout:
WARN [main] (Main.java:14) - Variable is not initiated!


You can also use other layouts such as HTMLLayout, DateLayout, XMLLayout etc.

7. Last step is to incorporate logging in your java class. To do this, Create a Class in the package you have created in Step 3. Right Click the package > New > Class > Class Name: LoggingSample.java


Now Copy and Paste the below code in LogginSample.java class.

package test;
import org.apache.log4j.Logger;
import java.io.*;
public class LoggingSample {
 private static Logger logger=Logger.getLogger("LoggingExample");
  public static void main(String[] args){
   try{
      FileInputStream fstream = 
                         new FileInputStream("D:\\textfile.txt");
      DataInputStream in = 
                         new DataInputStream(fstream);
      BufferedReader br = 
                  new BufferedReader(new InputStreamReader(in));
      String strLine;
      while ((strLine = br.readLine()) != null){
    System.out.println (strLine);
      }
      in.close();
   }catch (FileNotFoundException fe){
    logger.error("File Not Found",fe);
        logger.warn("This is a warning message");
        logger.trace("This message will not be logged since log  
                      level is set as DEBUG");
   }catch (IOException e){
    logger.error("IOEXception occured:", e);
  }
 }
}



In the above code I am trying to read a file which does not exist. The log that is generated
on the console is,

ERROR [main] (LoggingSample.java:19) - File Not Found
java.io.FileNotFoundException: D:\textfile.txt (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at test.LoggingSample.main(LoggingSample.java:10) 
WARN [main] (LoggingSample.java:20) - This is a warning message

At the same time log file is generated at \workspace\LoggingExample\logs\testlog.log with the following content,


2012-07-21 23:58:21,694 - LoggingExample - ERROR - File Not Found
java.io.FileNotFoundException: D:\textfile.txt (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at test.LoggingSample.main(LoggingSample.java:10)
2012-07-21 23:58:21,699 - LoggingExample - WARN - This is a warning message

Please note that in the above output, TRACE level message is not generated since it's priority is lower than that of DEBUG level which we have set in our log4j.properties file, while WARN level message is logged since it's priority is higher than that of DEBUG level

Please leave your comments and queries about this post in the comment sections in order for me to improve my writing skills and to showcase more useful posts. 

Subscribe to GET LATEST ARTICLES!


advertise here

Related

Trending 5802559769676873265

Post a Comment

  1. Excellent Post! Very simple and easy to understand.. Thanks for sharing!

    ReplyDelete
    Replies
    1. Hello Freind,
      I really really really thank you....
      After follows your steps, I got all idea of log4j, other wise it deficult for me...

      Delete
  2. Nice one!!, it is very helpful for testing our code. Thanks!

    ReplyDelete
  3. Plain, Simple and Excellent. Well Done !!

    ReplyDelete
  4. Replies
    1. Very simple and understandable. I am lucky to find this site.
      Thank you so much

      Delete
  5. Thanks you..Thank you...very much...
    If i have more then one class in single package ..
    how do i use the same logging feature

    ReplyDelete
    Replies
    1. Thanks for a giving a best examples for learners

      Delete
  6. Hi Priya ,
    I got it ..anyway..
    for each Class file user has to Logger

    import org.apache.log4j.Logger;

    After that in each class user has to add the below line for the class
    private static Logger logger=Logger.getLogger("CLASSNAME");

    After that
    just Add the loging message .


    :)

    ReplyDelete
    Replies
    1. Thank you for posting the information here!

      Thanks,
      Priya

      Delete
  7. Gud work nice clean and simple ..................many people would get benefited from ur post. Would look forward to ur other posts ............

    ReplyDelete
  8. thanxx priya...

    Thank u sho muchh....
    :-)

    ReplyDelete
  9. Excellent article to get started with Log4J!

    ReplyDelete
  10. nice article very much helpful

    ReplyDelete
  11. Thank you, straight forward and simple.

    ReplyDelete
  12. very good post. Thanks!!
    really appreciated.
    But i run my project via ant so please add how system will come to know about log4j.properties file.
    Please refer this: http://stackoverflow.com/questions/17517877/log4j-properties-configuration-issues-along-with-ant-configuration

    ReplyDelete
  13. Thanks for the good tutorial. There's one error: you have set the log level as "INFO" instead of "DEBUG".

    I have not been able to understand the significance of %5p in the log4j.properties file

    ReplyDelete
    Replies
    1. Hi ankiit,

      It is definitely not an error to set log level as INFO instead of DEBUG as I have chosen INFO as per my requirement and you can very well choose DEBUG level for your requirement. Generally for development environment INFO level is recommended while for Production environments DEBUG would suffice.

      %5p - Log Level. You can read the "explanation of configuration file" section in the above article again to understand this.

      Thanks,
      Priya

      Delete
    2. Hi Priya,

      I think I have been misunderstood here. I wanted to say that you've set the log level as INFO in the log4j.properties file. But there's a typo error in the text following the description of the properties file. Please find the reference to the typo error:-

      " If you specify the log level as WARN, then the INFO, DEBUG and TRACE log level messages will be omitted while the WARN, ERROR and FATAL log level messages will be logged. In our example we have set the log level as DEBUG which means TRACE level logs will not be logged.
      "

      Delete
    3. Hi ankiit,

      I fixed the mismatch in the explanation and implementation as you pointed out. Thank you so much for pointing this out. Also, I was wrong in my previous comment, for production environment WARN or ERROR level is recommended and not DEBUG level.

      Thanks,
      Priya

      Delete
  14. thanks a lot. very useful post. helped me a lot

    ReplyDelete
  15. Excellent post! I looked for guide just like this! thank you!

    ReplyDelete
  16. Hi Priya,

    First Thanks for the post ,it is really helpful for the beginners who are using Log4j..

    i have small question ..If i want to save console log into xls instead of notepad ,what to do???

    I'm very new to Log4j...so could you please tell me..



    ReplyDelete
    Replies
    1. First of all, not a good idea to use excel sheets for logging, instead use a database, from which you can export data to excel sheets anytime. If you cannot do anything with your requirement, then you may have to create your own log4j appender using Apache POI library to output logs to excel sheet. I have not done this before. If you are successful in doing it, let me know.

      Delete
  17. hiii, very nice way of explaining log4j , thank you miss . actually i m learning struts and i want to implement log4j in my struts project , i am very new to log 4j , so will you post a struts program using log4j ????

    thank you
    Gaurav

    ReplyDelete
  18. Exelente.!!! Accurate and direct.

    Thank you

    ReplyDelete
    Replies
    1. Thanks for such a wonderful post. Really helped a lot.

      Delete
  19. Thanks a lot and lot Priya.. i have struggled to create logs for past 2 weeks.. now i got solution..
    thanks..

    ReplyDelete
  20. Hi, I am using log4j for my automation scripts and it is working fine when i run multiple test one by one but i am facing problem in parallel run. I am running my tests parallelly and log files used to get generate for every tests but when i check them, all the logs gets messed up with each other. have your ever faced it? or do you have any solution regarding the same. I running my tests on Testng.
    Thanks

    ReplyDelete
  21. Best article ever seen by me ! very nice post.
    Thanks lot Priya Darshini.
    Tell me your other articles or posts about other concepts .
    I would like to read it.

    ReplyDelete
  22. Thank u for your nice post.
    Can you please explain in a java web application project where to use which( trace(), error(),info(), debug() etc) method?

    ReplyDelete
  23. Replies
    1. Thanks a lot. Excellent Post.

      Delete
    2. Hi Priya,
      Can you please tell me how to achieve logging via a socket using log4j, means i am using an small application and i want log4j to log the messages for all the users using my application.In this case how they can use my log4j sample to give a common place for logging messages.

      Delete
  24. Keep it up Priya! Very well presented

    ReplyDelete
  25. Really helpful. Thank you much, Priya.

    ReplyDelete
  26. Thanks for such a wonderful post. Really helped a lot.

    ReplyDelete

  27. Thanks, the example was very productive.

    ReplyDelete
  28. THANK U SOOOOOO MUCH.. IT WAS OF IMMENSE HELP FOR ME....

    ReplyDelete
  29. How to configure log4j to create diffrent log files for diffrent packages in my src. An example is much appriciated

    ReplyDelete
  30. I got it to work with diffrent log files
    ###################################

    log.dir=./logs
    archive.dir=${log.dir}/archive
    datestamp=yyyy-MM-dd/HH:mm:ss.SSS/zzz
    roll.pattern.hourly=.yyyy-MM-dd.HH
    roll.pattern.daily=.yyyy-MM-dd

    # Log levels
    log4j.rootLogger=CONSOLE,defaultLog

    ##### console appender ###########

    log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
    log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
    log4j.appender.CONSOLE.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n
    log4j.appender.CONSOLE.Threshold=WARN

    ##### console appender ###########

    ##### Default Application Logger ###########

    log4j.appender.defaultLog=org.apache.log4j.DailyRollingFileAppender
    log4j.appender.defaultLog.DatePattern=${roll.pattern.daily}
    log4j.appender.defaultLog.File=${log.dir}/ECometALLAppLogs.log
    log4j.appender.defaultLog.layout=org.apache.log4j.PatternLayout
    log4j.appender.defaultLog.layout.ConversionPattern=%d{${datestamp}} [%t] %-5p %m%n
    log4j.appender.defaultLog.Threshold=TRACE

    ##### Default Application Logger ###########

    ##### Application Logger Unit Test###########

    log4j.logger.test.main.java.com.xxx.concept=INFO,junitLogs
    log4j.additivity.test.main.java.com.xxx.concept=false
    log4j.appender.junitLogs=org.apache.log4j.DailyRollingFileAppender
    log4j.appender.junitLogs.File=${log.dir}/junit.log
    log4j.appender.junitLogs.DatePattern=${roll.pattern.hourly}
    log4j.appender.junitLogs.layout=org.apache.log4j.PatternLayout
    log4j.appender.junitLogs.layout.ConversionPattern=%d{${datestamp}}%p%m%n
    #log4j.appender.junitLogs.MaxFileSize=200KB
    #log4j.appender.junitLogs.MaxBackupIndex=2

    ##### Application Logger Unit Test###########

    ReplyDelete
    Replies
    1. Good that you figured it out yourself!

      Delete
  31. its a very good article thnk u.

    ReplyDelete
  32. hi. does it work similarly for a servlet?

    ReplyDelete
  33. Very Useful. Thanks so much.

    ReplyDelete
  34. i am new to Java. It is a wonderful post Thanks for it.

    ReplyDelete

emo-but-icon

Currency Converter

Built using AngularJS and ASP.NET Web API

SUBSCRIBE


item