Log4j Example.
Logging is a very important part of programming that provides advanced debugging capabilities and structured organization of information recorded at the run time. System.out.println (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.
Kindly follow the below steps for implementing logging with log4j in a simple Java Application using MyEclipse IDE with appropriate code and screenshots.
1) To get log4j jar file
click here
2) Open MyEclipse IDE and create a Java Project and name it and click on next and finish button.
3) Create a package , by right clicking on 'src' in Package Explorer > New > Package, I have named this package as 'test'.
4) Now 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.
5) In the Java Build Path dialogue, go to Library tab, Click Add External JARs and add the log4j-xxx.jar and Click OK.
6)Now create a file named as "log4j.properties" in your default package . 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.
7) Copy the below code to the log4j.properties file .
# 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
8) Last step is to incorporate logging in your java class. To do this, Create a Class in the package you have created Right Click the package > New > Class > Class Name:Simple.java
Now Copy and Paste the below code in Simple.java class.
package test;
import org.apache.log4j.Logger;
import java.io.*;
public class Simple{
private static Logger logger=Logger.getLogger("Log4jExample");
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 Existed",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);
}
}
}
n 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] (Simple.java:20) - File Not Found
java.io.FileNotFoundException: D:\textfile.txt (The system cannot find the path specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at test.Simple.main(Simple.java:9)
WARN [main] (Simple.java:21) - This is a warning message
At the same time log file is generated at \workspace\Simple\logs\testlog.log with the following content,
2014-04-18 09:32:23,337 - Log4jExample - ERROR - File Not Found
java.io.FileNotFoundException: D:\textfile.txt (The system cannot find the path specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at test.Simple.main(Simple.java:9)
2014-04-18 09:32:23,342 - Log4jExample - WARN - This is a warning message.