User Tools

Site Tools


java:log4j

This is an old revision of the document!


Logging with log4j

Code Snippets

	private static Logger logger = Logger.getLogger(MyClass.class);
...
	logger.info("BUTTON step backward");
...
	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");

Rationale

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

log4j vs. JDK logging

Since JDK 1.4 there is a logging framework inside the Java core packages.

AFAIK log4j provides more features and is at least as stable, so I keep using log4j.

Read more opinions http://www.google.at/search?q=log4j+java.util.logging

log4j vs. Commons Logging

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

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 and 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 is 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, then load this file
    • 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.1256038629.txt · Last modified: 2009/10/20 13:37 by Alexander Rind

alex @ ieg: home about me publications research