Using a single log4j logger in a standalone Java application

I have code that is a standalone java application consisting of 30+ classes.

Most of them inherit from some other base classes.

Each class has this method for getting and using log4j logger

public static Logger getLogger() {
    if (logger != null) return logger;
    try {
        PropertyUtil propUtil = PropertyUtil.getInstance("app-log.properties");
        if (propUtil != null && propUtil.getProperties() != null)
            PropertyConfigurator.configure(propUtil.getProperties ());
        logger = Logger.getLogger(ExtractData.class);
        return logger;
    } catch (Exception exception) {
        exception.printStackTrace();
    }
}

A) My question is whether it needs to be reorganized into some kind of general journal, which is initialized once and used by all classes? Is this the best practice?

B) If yes, how can this be done? How can I pass the magazine?

C) It is actually used in the code not as Logger.debug(), but getLogger().debug(). What is the impact of this in terms of performance?

+3
source share
3 answers

A) Log4J, , . , . :

private static final Logger logger = Logger.getLogger(MyClass.class);

, () . , , INFO DEBUG , . .

B) , , , :

private static final Logger logger = Logger.getLogger();

C) , , , , JIT- . .

, , , , - Log4J, log4j.properties . , Log4J .

private static final Logger logger = Logger.getLogger(ExtractData.class);

private static Logger getLogger() {
    return logger;
}

. , getLogger, .

, getLogger public, .

+8

A) , , log4j. , , .

B) , Logger.getLogger() .

C) , . , getLogger() final, , . , , , , , , .

+3

Each class can get its own journal as

final static private Logger log = Logger.getLogger("com.company.package.MyClass");

This allows you to configure log4j parameters according to a class that is more flexible than the standard logger.

0
source

Source: https://habr.com/ru/post/1749945/


All Articles