0

Existing code is setting up logger programmatically. Thats how it does it

public void init (String logFile, Logger logger){
    Validate.isTrue(logger.getAppender(APPENDER_NAME) == null, "Logger has configured project appender");

    //remaining code
}

now, i have changed logger object from log4j logger to org.slf4j.Logger and getting error that getAppender method doesn't exist. What should be the alternate here.

Em Ae
  • 8,167
  • 27
  • 95
  • 162
  • Why do you configure the logger programmatically? Also, I'm guessing that you're migrating from log4j1 to slf4j + log4j2 but can you please confirm if this is really the case? – D.B. May 05 '18 at 22:58

1 Answers1

0

I am afraid that's not possible by using slf4j API.

slf4j is a logger facade API and exposes only high-level methods like debug, trace, etc. It doesn't have notion of appenders, which is implementation detail of concrete underling logging, like log4j.

Excerpt from SLF4J FAQ:

SLF4J is only a facade, meaning that it does not provide a complete logging solution. Operations such as configuring appenders or setting logging levels cannot be performed with SLF4J. Thus, at some point in time, any non-trivial application will need to directly invoke the underlying logging system. In other words, complete independence from the API underlying logging system is not possible for a stand-alone application. Nevertheless, SLF4J reduces the impact of this dependence to near-painless levels.

The same is true for log4j2 API as well.

What are the options:

  1. Separate part of code, which will be coupled with log4j logger and do required configurations and validations there.

  2. Another approach is to cast slf4j logger to log4j after check:

    // log4j 1.x
    if (logger instanceof org.apache.logging.log4j.core.Logger) {
       org.apache.log4j.Logger log4j = (org.apache.log4j.Logger) logger;
       // access to log4j.getAppender("APPENDER_NAME");
    }
    
Igor Golovin
  • 64
  • 1
  • 8