Where to define a static application logger?

I have several packages in my Java web application. In some of them, I use this construct:

public class Foo {
  private static Logger logger = LoggerFactory.getLogger("com.XXX");
  public void bar() {
    Foo.logger.debug("Method bar() was just called");
  }
}

Of course, this is just an example. Everything works fine, but I donโ€™t like the idea of โ€‹โ€‹initializing the log in many classes. This is an obvious duplication of code. I would like to move it to some helper class and allow all other classes to access it. Is this the right idea? Or maybe there is another โ€œbest practiceโ€ or pattern?

+5
source share
7 answers

, . :

public class MyLogger {
  private static Logger logger = LoggerFactory.getLogger("application");

  public static void debug(String s) {logger.debug(s));}

  public static void debug(Class<?> caller, String s) {
     LoggerFactory.getLogger(caller.getName()).debug(s);
  }

  // ...
}

:

import static MyLogger.*;

public class Foo {
  public void bar() {
    // makes use of static import!
    debug("Method bar() was just called"); 
    debug(this.getClass(), "Method bar() was just called"); 
  }
}

โ€‹โ€‹ debug delegate, Logger.

+3

, , , import java.util.* 75% - . public class .... . .

- , . , . .

, , .

+8

, -, logger constrcut, Log4J/inits.

private static Logger logger = LoggerFactory.getLogger("com.XXX");
logger.info("Hello World");

-

GlobalLogger.info(this, "LogMessage");  //Singleton...

... "".

+5

, Log4j ( , ), . , , .

+1

(.. Log4j) .

, Log4j NextBigThingLogger, MyLogger .

.

API Apache Java " ", , .

+1

. , . Singleton.

public class LoggerAdapter extends Logger {
    private LoggerAdapter instance;
    private Logger logger;

    private LoggerAdapter() {

    }

    public static LoggerAdapter getInstance(Clazz<?>  clazz) {
        if (instance == null) {
            instance = new LoggerAdapter();
        }
        instance.logger = logger = LoggerFactory.getLogger(clazz.getName());

        return instance;
    }

    @Override
    public void trace(Object object) {
        logger.trace(object);
    }

    //Other overridden methods here...
};

, ....

0
source

All Articles