User Tools

Site Tools


java:log4j

Logging with log4j

Code Snippets

	private static Logger logger = Logger.getLogger(MyClass.class);
...
	logger.fatal("text");
	logger.error("text");
	logger.warn("text");
	logger.info("text");
	logger.debug("text");
	logger.info("text");
...
	if (logger.isTraceEnabled())
		logger.trace("lo: " + lo + " hi: " + hi + " min: " + min + " max: " + max + " rel: " + rel);
...
	if ((new File("log4j.properties")).canRead())
		PropertyConfigurator.configure("log4j.properties");

log4j.properties

log4j.rootLogger=TRACE, A1
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout

# Print the date in ISO 8601 format
log4j.appender.A1.layout.ConversionPattern=%d [%t] %-5p %c - %m%n

log4j.logger.gui.MainFrame=INFO
        try {
            if ((new File("log4j.properties")).canRead())
                PropertyConfigurator.configure("log4j.properties");
        }
        catch (SecurityException e) {
        }

Rationale

… because it is easier than // System.out.println(...) all over the code

log4j vs. JDK logging

log4j vs. Commons Logging

Commons Logging seems to be a compatibility layer so that a library can work with different logging implementations.

newer logging packages

Good Practice

Whatever you do, don't break your program: If the program reads a log4.properties file from the file system, the file will likely get lost and users will be confronted with a FileNotFoundException or might not be able to run the program.

Here is a solution that works well for me:

  1. a default log4j.properties file is located in the root directory of the classpath
    • if you work with Eclipse, this will be your ./src directory
    • if you create a jar-file, this will be the root directory of the jar-file
    • for the default settings use minimal logging (e.g., ConsoleAppender, WARN level)
  2. a customized log4j.properties file can be located in the working directory
    • if you work with Eclipse, this will be the project directory
  3. in the main method check, whether log4j.properties exists in the working directory
    • if it exist and is readable, then load this file
    • handle SecurityException (e.g., for Java Web Start)
    • if it does not exist, log4j will load the file from the classpath by default
  4. if users want to override this behavior, they can
    • delete the log4j.properties from the working directory AND
    • specify the url of the configuration as a Java system property (e.g., -Dlog4j.configuration=file:/home/alex/log4j.properties)

Ressources

java/log4j.txt · Last modified: 2012/01/04 10:30 by Alexander Rind

alex @ ieg: home about me publications research