简体   繁体   中英

inheriting log4j Logger

I'm planning to replace old logger with log4j one. Instead of using Logger directly I need to create new class LocalLogger inherited of Logger. Reason of doing that - I need new logging method names that was available in old logger.

I have log4j logger:

protected final Logger logger = Logger.getLogger(getClass());

How to make function that could make LocalLogger in the same way like Logger does?

How to pass class c to super LocalLogger?

Draft for the LocalLogger:

public class LocalLogger extends Logger{

    protected LocalLogger(String name) {
        super(name);
    }

    public LocalLogger getLocalLogger(Class c)
    {
        return new LocalLoger(???)
    }

}

I would recommend you don't extend Logger in this instance. Instead, use the delegation pattern .

Create a brand new class with the methods you wish to have, but delegate the logging calls to an internal instance of Logger :

public class LocalLogger {

  private final Logger logger;

  public LocalLogger(String name) {
    logger = Logger.getLogger(name);
  }

  public LocalLogger(@SuppressWarnings("rawtypes") Class clazz) {
    logger = Logger.getLogger(clazz);
  }

  public void antiqueLoggingMethod(String msg) {
    logger.info(msg);
  }

  // etc.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM