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(); } }
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:
- Invoking Class Methods using Reflection in Java
- Understanding Prototype Design Pattern in Java
- Sending Exceptions Email Using Apache Log4J
- Logging User Session details using Apache log4j
- Reading Microsoft Word Document in JAVA
- Remote URL Connection Through Proxy in Java
- Singleton Design Pattern in Java
- Checking Image Resolution from Java Applications
- Ajax Programming with JSP and Servlets
- HTTP Form POST Request using AJAX and Servlet


































