Friday, 12 September 2014

Logging with log4j Example :Java..Eclips

Logging with log4j Example :Java


JVM Hosting

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.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.



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

No comments:

Post a Comment