Logging with log4j Example :Java
Logging is a very important part of programming that provides advanced debugging capabilities and structured organisation of informatio...
https://www.programming-free.com/2012/07/implement-logging-with-log4j-in-java.html
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 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,
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
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.
Excellent Post! Very simple and easy to understand.. Thanks for sharing!
ReplyDeleteHello Freind,
DeleteI really really really thank you....
After follows your steps, I got all idea of log4j, other wise it deficult for me...
Nice one!!, it is very helpful for testing our code. Thanks!
ReplyDeletePlain, Simple and Excellent. Well Done !!
ReplyDeleteThank you!
DeleteThank you.. really helped me ..
ReplyDeleteMost Welcome!
DeleteVery simple and understandable. I am lucky to find this site.
DeleteThank you so much
Thanks you..Thank you...very much...
ReplyDeleteIf i have more then one class in single package ..
how do i use the same logging feature
Thanks for a giving a best examples for learners
DeleteHi Priya ,
ReplyDeleteI 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 .
:)
Thank you for posting the information here!
DeleteThanks,
Priya
Thank you :D
ReplyDeleteMost Welcome!
DeleteGud work nice clean and simple ..................many people would get benefited from ur post. Would look forward to ur other posts ............
ReplyDeleteThank you!
Deletethanxx priya...
ReplyDeleteThank u sho muchh....
:-)
Most Welcome!
DeleteGood one thanx .....priya :)
ReplyDeleteMost Welcome!
DeleteExcellent Post
ReplyDeleteThank you!
DeleteExcellent article to get started with Log4J!
ReplyDeletenice article very much helpful
ReplyDeleteThank you, straight forward and simple.
ReplyDeleteMost welcome!
Deletevery good post. Thanks!!
ReplyDeletereally 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
Good Post. Thanks!!!
ReplyDeleteThanks for the good tutorial. There's one error: you have set the log level as "INFO" instead of "DEBUG".
ReplyDeleteI have not been able to understand the significance of %5p in the log4j.properties file
Hi ankiit,
DeleteIt 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
Hi Priya,
DeleteI 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.
"
Hi ankiit,
DeleteI 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
thanks a lot. very useful post. helped me a lot
ReplyDeleteExcellent post! I looked for guide just like this! thank you!
ReplyDeleteThank you and most welcome :)
DeleteThanks... really useful.
ReplyDeleteHi Priya,
ReplyDeleteFirst 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..
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.
Deletehiii, 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 ????
ReplyDeletethank you
Gaurav
Nice work
ReplyDeleteExcellent post... thanks alot
ReplyDeleteExelente.!!! Accurate and direct.
ReplyDeleteThank you
Thank you for the feedback!
DeleteThanks for such a wonderful post. Really helped a lot.
DeleteThanks a lot and lot Priya.. i have struggled to create logs for past 2 weeks.. now i got solution..
ReplyDeletethanks..
Most Welcome!
DeleteHi, 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.
ReplyDeleteThanks
Good one
ReplyDeleteThank u for your nice post.
ReplyDeleteCan you please explain in a java web application project where to use which( trace(), error(),info(), debug() etc) method?
Chevere
ReplyDeleteGracias
DeleteThanks a lot. Excellent Post.
DeleteHi Priya,
DeleteCan 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.
Keep it up Priya! Very well presented
ReplyDeleteReally helpful. Thank you much, Priya.
ReplyDeleteThanks for such a wonderful post. Really helped a lot.
ReplyDelete
ReplyDeleteThanks, the example was very productive.
good one priya
ReplyDeleteTHANK U SOOOOOO MUCH.. IT WAS OF IMMENSE HELP FOR ME....
ReplyDeleteMost welcome!
DeleteHow to configure log4j to create diffrent log files for diffrent packages in my src. An example is much appriciated
ReplyDeleteI got it to work with diffrent log files
ReplyDelete###################################
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###########
Good that you figured it out yourself!
Deleteits a very good article thnk u.
ReplyDeletereally nice
ReplyDeletehi. does it work similarly for a servlet?
ReplyDeleteExcellent Post! Thank You
ReplyDeleteVery Useful. Thanks so much.
ReplyDeletei am new to Java. It is a wonderful post Thanks for it.
ReplyDeleteIts a Nice Post to Learn JAVA
ReplyDeleteThanks,now i am understand the log4j
ReplyDeleteExtremely helpful, made the concept pretty clear. Thank you mate
ReplyDeleteMost Welcome!
Deletev nice.but i would like to know wat is the purpose of .txt file?
ReplyDeleteNot able to copy the code from your article. Tried in Firefox and Chrome. idk what's wrong.
ReplyDeleteI deleted the class="post" from the div tag of your post in the Inspect view of the browser. Now I am able to select the code and copy :)
DeleteThis comment has been removed by the author.
ReplyDeletelog4j.category.Test=ERROR, TestLog
ReplyDeletelog4j.additivity.Test=false
log4j.appender.TestLog=org.apache.log4j.DailyRollingFileAppender
log4j.appender.TestLog.encoding=UTF-8
log4j.appender.TestLog.File=/Logs/test.log
log4j.appender.TestLog.MaxFileSize=4096KB
log4j.appender.TestLog.MaxBackupIndex=10
log4j.appender.TestLog.DatePattern = .yyyy-MM-dd
log4j.appender.TestLog.layout=org.apache.log4j.PatternLayout
log4j.appender.TestLog.layout.ConversionPattern=%d{ISO8601} %5p %c %m%n
When no error empty log file is not getting generated
Any clue on this?
I need to create empty file even if there is no error
That was great post.
ReplyDeleteJava Classes in Nagpur
amazing writeup. keep posting java classes in pune
ReplyDeleteThanks for sharing!!!
ReplyDelete