User Tools

Site Tools


Logging with log4j

Code Snippets

	private static Logger logger = Logger.getLogger(MyClass.class);
	if (logger.isTraceEnabled())
		logger.trace("lo: " + lo + " hi: " + hi + " min: " + min + " max: " + max + " rel: " + rel);
	if ((new File("")).canRead())

log4j.rootLogger=TRACE, A1

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

        try {
            if ((new File("")).canRead())
        catch (SecurityException e) {


… 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 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 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 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 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 from the working directory AND
    • specify the url of the configuration as a Java system property (e.g., -Dlog4j.configuration=file:/home/alex/


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

alex @ ieg: home about me publications research