Hem » Java » Set up logging in a Java webapplication

Set up logging in a Java webapplication

There’s a lot of sources on the net for configuring and using the different logging frameworks in Java, so i’m just going to show you how you can use an listener for initializing a Log4J configuration in an Web application.

Put the listener-init in your web.xml


The listener (also using Apache Commons ConfigurationUtils)

public class Log4jConfigListener implements ServletContextListener {

    public void contextInitialized(ServletContextEvent sce) {
        URL configUrl = null;

        ServletContext servletContext = sce.getServletContext();
        String log4jConfigName = servletContext.getInitParameter("log4jConfigLocation");

        // Try to locate file in classpath
        configUrl = ConfigurationUtils.locate(log4jConfigName);

        if (configUrl != null) {
            //if the location is other than the root

    public void contextDestroyed(ServletContextEvent sce) {
        //cleanup or be forever silent

and that should be it!

Some other things of usage when logging:

  • If you run with ”-Dlog4j.debug” then log4j will print out info to standard output telling how it is trying to configure itself. Looking through that will tell you where it is looking for the config file.
  • And Please, do use SLF4J even if you use Log4J (or another logging framwork) for your logging. It’s a drop-in replacement for many logging frameworks with too many benefits to write about here.
  • Static or new instance’s for your loggers? The pattern for getting a logger is usually like this:
package some.package;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MyClass {
       final (static) Logger logger = LoggerFactory.getLogger(MyClass.class);
... etc

but some argue that you should make new instances. SLF4J has an little interesting read, and recommends static.

Oh, BTW, here’s an alternative way to do the same as in this post, but without a listener.


Fyll i dina uppgifter nedan eller klicka på en ikon för att logga in:

WordPress.com Logo

Du kommenterar med ditt WordPress.com-konto. Logga ut /  Ändra )


Du kommenterar med ditt Google-konto. Logga ut /  Ändra )


Du kommenterar med ditt Twitter-konto. Logga ut /  Ändra )


Du kommenterar med ditt Facebook-konto. Logga ut /  Ändra )

Ansluter till %s