Programmatically logging using Apache Log4J

We normally create log4j.properties files to perform logging inside java code. But we can also do the same logging programmatically without creating log4j.properties file. This article will show you a small code snippet that allow us to achieve the same.

import java.io.IOException;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.SimpleLayout;
import org.apache.log4j.FileAppender;
 
public class Log4J {
	static Logger logger = Logger.getLogger(Log4J.class);
	SimpleLayout layout = new SimpleLayout();
	FileAppender appender = null;
 
	public Log4J() {
		try {
			appender = new FileAppender(layout, "/home/hitesh/javalog.log", false);
			logger.addAppender(appender);
 
			logger.setLevel((Level) Level.DEBUG);
 
			logger.debug("Printing DEBUG Statements");
			logger.info("Printing INFO Statements");
			logger.warn("Printing WARM Statements");
			logger.fatal("Printing FATAL Statements");
 
		}
		catch(IOException e) {
			e.printStackTrace();
			logger.error("Printing ERROR Statements",e);
		}
	}
 
	public static void main(String args[]) {
		Log4J a = new Log4J();		
	}
}

Your email:

 


You would require the Apache LOG4J Library which can be downloaded from Apache LOG4J.

As you can see in java code we are defining the appender and layout that we will be using for configuring log4j for our application. For more information on appenders and layout please refer to the Apache LOG4J API. While setting the FileAppender we pass the fileName where we want to log the content and boolean value indicating whether we want to append the log or not. TRUE – Append the Log Content and FALSE – Do not append the Log Content.

Custom Search


Popular Articles:

Categories: Java Tags:
  1. No comments yet.
  1. No trackbacks yet.