1

I need to get class and method names to Log4j logger. What is the best way of doing that? Also I would like to create one instance of logger for whole application - it is quite boring to declare logger in each class. What is the way to solve these problems.

3 Answers 3

3

You can use %C and %M placeholders in your PatternLayout. Please be advised, their use is not recommended for performance reasons.

There are several ideas on how to avoid declaring loggers for each class. For example, if creating a common base class is a viable option, you can declare a protected final logger like this:

abstract class Base {

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

}

class Concrete extends Base {

    public void testLogger() {
        logger.info("It works!");
    }

}

Or, you may try injecting loggers with a dependency injection framework such as Weld.

Sign up to request clarification or add additional context in comments.

Comments

0

Actually, creating one Logger for whole application, is not a good idea at all. It's easy to mess up loggers, levels of logging, configuration, etc.

But, if you still want it, you could create a logger instance in main method, and pass it for each of the class (e.g. using setLogger() in every class you use or passing as argument to class constructor). But again, is 100% bad idea to do this.

Comments

0
  1. make your Logger Instance static
  2. Every class has its own Logger => Logger.getLogger(xyz.class)
  3. Use 2. than you can configure log4j

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.