Configure Log4j on Java Console Applications
This example demonstrated how to configure Log4j setup using the Proerties file. This example program uses simple satndalone java program for running the example. But, in most of the project scenarios it will be used in the web application. However the configuration file will be the same.Steps to follow:
Step1: Download log4j jar from log4j main site (or http://www.java2s.com/Code/Jar/JKL/Downloadlog4jjar.htm) and add to your project lib.
Step2: Create a property file log4j.properties
and make sure that it is available to java file(Or modify the path in java file)
Step3: Create a Log4jPropertyTest.java file with below mentioned java code(Log4jPropertyTest.java)
Step4: Compile and run the Log4jPropertyTest.java file
Step5: log4j.appender.Appender1.File=c:\\sample.log
is the actual log file created after running Log4jPropertyTest java file.
log4j.properties
# Set root logger level to DEBUG and its only appender to Appender1. |
Log4jPropertyTest.java
package com.chandra.log4j; import org.apache.log4j.Category; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; /** * source : http://javacodehelp.blogspot.com/ */ public class Log4jPropertyTest { private static Logger logger = Logger.getLogger(Log4jPropertyTest.class .getName()); public static void main(String args[]) { PropertyConfigurator.configure("c:\\log4j.properties"); logger.info("Test Log"); Log4jPropertyTest.read(); Category root = Category.getRoot(); root.debug("Message 1"); } public static void read() { logger.debug("Great!!!"); System.out.println("You are in read method"); } } |