log4J

log4j is a Java-based logging utility.  In general, for debugging an application that is to know the status of a java application at its execution time, we use sysout statements in the application. Some of the disadvantages of using sysout :

  • Generally sysout are printed on console, so there are temporary messages and when ever the console is closed then automatically the messages are removed from the console.
  • All the appliation will print sysout in one place, sysout.log or consle , making it difficult which application printed what.

Log4j is a tool to help the programmer output log statements to a variety of output targets like  a file or database. Log4j has three main components:

  • loggers: Responsible for capturing logging information.
  • appenders : Responsible for publishing logging information to various preferred destinations.
  • layouts: Responsible to format logging information in different styles.

There are various different log levels:

  • ALL All levels including custom levels.
  • DEBUG Designates fine-grained informational events that are most useful to debug an application.
  • INFO Designates informational messages that highlight the progress of the application at coarse-grained level.
  • WARN Designates potentially harmful situations.
  • ERROR Designates error events that might still allow the application to continue running.
  • FATAL Designates very severe error events that will presumably lead the application to abort.
  • OFF The highest possible rank and is intended to turn off logging.

Lets write a sample class to see this. Download log4j jar and add it into class path or lib. Log4jExample.java


package mynotes.main;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
public class Log4jExample {
static final Logger logger = Logger.getLogger(Log4jExample.class);

private static void loadLog4jProperties(){
Properties props = new Properties();
//load from classpath
InputStream inputStream = Log4jExample.class.getClassLoader().getResourceAsStream("properties/log4j.properties");
try {
props.load(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
// Now pass these properties to PropertyConfigurator
PropertyConfigurator.configure(props);
}


public static void main(String[] args) {
loadLog4jProperties();
System.out.println("is DeBUG enabled=>"+logger.isDebugEnabled());
logger.debug("Sample debug message");
System.out.println("is info enabled=>"+logger.isInfoEnabled());
logger.info("Sample info message");
logger.warn("Sample warn message");
logger.error("Sample error message");
logger.fatal("Sample fatal message");
}
}

log4j.properties is a properties file that is under properties package. With the help of the properties file you can change the logging level, switch on or off logging at anytime, send the logs to console or file system. Also, your different environmet will have different setup like DEBUG will be most likely disabled in production env, so you may have different properties file for diff env. PropertyConfigurator.configure needs to load config file only once in entire apllication.

log4j.properties


# Root logger option
log4j.rootLogger=INFO,stdout

# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

Now the logs will be printed in the console.


is DeBUG enabled=>false
is info enabled=>true
2014-08-31 14:18:02 INFO Log4jExample:33 - Sample info message
2014-08-31 14:18:02 WARN Log4jExample:34 - Sample warn message
2014-08-31 14:18:02 ERROR Log4jExample:35 - Sample error message
2014-08-31 14:18:02 FATAL Log4jExample:36 - Sample fatal message

Notice that the DEBUG is false hence debug log didnt got printed. If you want to have file you can use following log4j.properties


# Root logger option
log4j.rootLogger=INFO, file

# Direct log messages to a log file

log4j.appender.file=org.apache.log4j.RollingFileAppender
#Redirect to Tomcat logs folder
#log4j.appender.file.File=${catalina.home}/logs/logging.log
log4j.appender.file.File=C:\\logigng.log
log4j.appender.file.MaxFileSize=10MB
log4j.appender.file.MaxBackupIndex=10
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

For both


# Root logger option
log4j.rootLogger=INFO, file ,stdout

# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
#Redirect to Tomcat logs folder
#log4j.appender.file.File=${catalina.home}/logs/logging.log
log4j.appender.file.File=C:\\logigng.log
log4j.appender.file.MaxFileSize=10MB
log4j.appender.file.MaxBackupIndex=10
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

Use appropriate log levels at different places.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: