How do I configure Log4J with properties?
Author: Deron Eriksson
Description: This Java tutorial describes how to configure Log4J via a properties file.
Tutorial created using:
Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 1.5.1
In an earlier lesson, I described Log4j and initialized logging in a small test application using the BasicConfigurator class. This is a nice starting point, but a much more practical approach is to initialize log4j in an application using properties. In your project, you need the log4j jarW file in the build path. I created a Log4JPropertiesTest class in this project. Log4JPropertiesTest is a very simple class that we'll use as a starting point to test out configuring Log4j via properties. Log4JPropertiesTest.javapackage test; import org.apache.log4j.Logger; public class Log4JPropertiesTest { static Logger log = Logger.getLogger(Log4JPropertiesTest.class); public static void main(String[] args) { log.debug("This is a debug message"); myMethod(); log.info("This is an info message"); } private static void myMethod() { try { throw new Exception("My Exception"); } catch (Exception e) { log.error("This is an exception", e); } } } I created an EclipseSW Debug Configuration for Log4JPropertiesTest. Since we want to really see what's going on with Log4j, let's add a VM argument instructing log4j to output additional information so we can tell what's going on behind the scenes. This argument is: -Dlog4j.debug=true If we click Debug, we can run our application. In the console window, we can see that log4j searches for a log4j.xml file and then searches for a log4j.properties file. It doesn't find either (since we haven't created either one of them), so it reports: log4j: Could not find resource: [null]. (Continued on page 2) Related Tutorials:
|