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 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.
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.
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".
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,
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.
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.
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.ConsoleAppenderlog4j.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.
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,
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
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.
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.
No comments:
Post a Comment