Logging in Java – Log4J

0
2246

History of Logging

Logging is a very important part of the development cycle. Writing the logs is a very old method to debug and monitor the code as well as your application. In the past, people used to do it by using output statements also called SOP statements in reference to Java. They were easy to write without any specific knowledge of logging framework but they do carry some drawbacks as well. For example, they can’t be stored for future reference; they can only be printed on console, we can’t use them to differentiate the different states of the code like debugging, error etc. So we need a framework which can give us many more features to debug our applications.

Introduction to Log4J

Log4J is widely used open source logging framework developed under Apache Project. It provides us a solution which is extendible, reliable, easily configurable and robust. All this makes Log4J the most favorite framework among Java developers for monitoring and debugging the applications. In Log4J we use the log statements instead of SOP statements, utilizing classes and interfaces of the Log4J framework. There are salient features of Log4J which make it really popular; like the format of the logs can be changed using LAYOUT feature, it’s thread safe and supports internationalization too. Log4J uses multiple levels, namely ALL, TRACE, DEBUG, INFO, WARN, ERROR and FATAL.

Log4j – Logging Levels

The org.apache.log4j.Level class provides following levels but you can also define your custom levels by sub-classing the Level class.

Level      Description
-----     -----------
DEBUG     To get information that is most useful to debug an application.
ERROR     To get the error event and log them.
FATAL     Designates very severe error events that will presumably lead the application to abort.
INFO      Informational message that highlight the progress of the application 
WARN      Designates potentially harmful situations
ALL (Sp. Level) All levels including custom levels.
OFF (Sp. Level) The highest possible rank and is intended to turn off logging.

Components of Log4J

There are basically 3 main components of Log4J
1) Logger – Responsible for capturing logging information
2) Appenders – Responsible for managing the output destination
3) Layouts – Responsible for managing the output formats

Log4J - Logging in Java
Log4J – Logging in Java

Lets discuss them in detail further:

Loggers

The logger component is accessible through the Logger class of the log4j API or we can say org.apache.log4j. This class provides a static method Logger.getLogger(name) that either retrieves an existing logger object by the given name or creates a new logger of given name if none exists. While creating a Logger object we need to pass either fully qualified class name or class object as a parameter.

Logger methods are used to generate log statements in a java class instead of SOP and for that you need to get the handle of logger for that class:

static Logger logger = Logger.getLogger(YourClassName.class.getName())

Now as described above there are levels of logging and we can set the level as shown below:

logger.setLevel((Level)Level.DEBUG);

Just like logging levels we have logging methods which we can use to log the messages. In total we have 5 logging methods in Logger Class namely debug(), info(), warn(), error(), fatal(). All different methods have different roles and purposes. The priority of them is :
debug < info < warn < error < fatal
Which means the level used for logging in your code, would actually display the logs for that level as well level for the levels below that. For Example: if the level id chosen as ‘Warn’, all the logs at Warn, info and debug would be shown.

Let’s see a small program :

import org.apache.log4j.Logger;
public class GoyalsbitLog {
   private static org.apache.log4j.Logger log = Logger.getLogger(GoyalsbitLog.class);
   public static void main(String[] args) {
      log.debug("This is a Debug Message!");
      log.info("This is a Info Message!");
      log.warn("This is a Warn Message!");
      log.error("This is a Error Message!");
      log.fatal("This is a Fatal Message!");
   }
}

When you compile and run LogClass program it would generate following result:

This is a Debug Message!
This is a Info Message!
This is a Warn Message!
This is a Error Message!
This is a Fatal Message!

There are two more special levels:
ALL Level – This one is used to turn on all the logging levels.
OFF Level – This one is used to turn off all the logging levels.

Appenders

One of the benefits of Log4J is that we can store the logs for future reference and that is because different types of appenders helps us to do that. Appender is basically an interface which store log statements in some files generated by Logger classes under different levels. Although we can implement the Appender interface to create our own custom ways to output the log but still the framework provides us some in-build appenders and the most common ones are:

File Appender– This one is the most common Appender and is used to log outputs in a file.
Rolling File Appender– It extends FileAppender to backup the log files when they reach a certain size.
DailyRollingFileAppender -It extends FileAppender so that the underlying file is rolled over at a user chosen frequency.
ConsoleAppender – It appends log events to System.out or System.err using a layout specified by the user. The default target is System.out.
JDBCAppender – This is used to append the logs in database.
SocketAppender – This is to append logs in remote storage.
Similarly we have many other appenders like TelnetAppender, WriterAppender, SyslogAppender, SMTPAppender etc.

Layouts

The output of an appender can be customized by associating with it a Layout .Apache log4j provides various Layout objects, each of which can format logging data according to various layouts. It is also possible to create a Layout object that formats logging data in an application-specific way.

Simple layout – (org.apache.log4j.SimpleLayout) This formats the output in a very simple manner, it prints the Level, then a dash ‘-‘ and then the log message.
PatternLayout – (org.apache.log4j.PatternLayout) This formats the output based on a conversion pattern specified, or if none is specified, the default conversion pattern.
HTML layout – (org.apache.log4j.HTMLLayout) This formats the output as a HTML table.
XMLLayout – (org.apache.log4j.xml.XMLLayout) This formats the output as a XML.

Now let’s see an example illustrating an appender as well as a layout:

import org.apache.log4j.Logger;
import org.apache.log4j.SimpleLayout;
import org.apache.log4j.FileAppender;

public class GoyalsbitAppender{
static Logger logger = Logger.getLogger(GoyalsbitAppender.class);
 public static void main(String args[]) {
   SimpleLayout layout = new SimpleLayout();
   FileAppender appender = null;
   try {
        appender = new FileAppender(layout,"output1.txt",false);
   } catch(Exception e) {}
   logger.addAppender(appender);
   logger.debug("Here is some DEBUG");
 }
}

References

1) http://logging.apache.org/log4j/2.x/
2) http://www.allapplabs.com/log4j/log4j.htm
3) http://www.javaworld.com/article/2076243/java-se/log4j-delivers-control-over-logging.html

NO COMMENTS

LEAVE A REPLY