Jack
Jack

Reputation: 6620

Do I need to have a static instance of Logger in all my classes to implement log4j?

Log4j perfectly works in conjunction with my application, but my question is that is there any other ever efficient approach to implementing it rather than having the following "logger" instance in all classes of my application?

public Class myClassName{
    private static Logger logger = Logger.getLogger("myClassName");

    public String myMethod(){
        try{
              ....
        }catch (Exception e) {
             logger.error("Location:MyMethod:" + e.getMessage());
             return "failed";
        }
    }
}

Upvotes: 4

Views: 1576

Answers (4)

Simulant
Simulant

Reputation: 20112

You could use one Logger for all your classes with the draw back that your log messages no longer show which of your classes called the logger, because all classes are using the same logger with a single name. Logger.getLogger("myClassName") is used to set the name of the logger to the class name so the classname is easily added to the log message by getting the loggers name.

This will also work, but is not recommanded:

public Class MyLogger{
    public static Logger logger = Logger.getLogger("myLoggerName");
}

--

public Class myClassName{
    public String myMethod(){
        try{
              //....
        }catch (Exception e) {
             MyLogger.logger.error("Location:MyMethod:" + e.getMessage());
             return "failed";
        }
    } 
}

I think you could add the class name by reflection (even if you just use one logger) but this would be very slow and is also not recommanded for productive use.

Upvotes: 2

J888
J888

Reputation: 1964

As TheLostMind suggested, you can use a code like following:

public class Logging {
    private static Logging instance;
    private static final Logger logger = Logger.getLogger("Logging");

    private Logging(){
    }

    public static synchronized Logging getInstance()
    {
        if (instance == null)
            instance = new Logging();

        return instance;
    }

    public static Logger getLogger() {
        return logger;
    }


}

Upvotes: 1

Kamal Kannan
Kamal Kannan

Reputation: 95

You need to have a static instance of the logger in the class.

It is better if you add final modifier since it is going to stay constant through all your instances. It is a good programming practice.

private static final Logger LOGGER = Logger.getLogger(ZPAction.class.getName());

Upvotes: 1

Hirak
Hirak

Reputation: 3649

In order to log messages, you need to have a log instance. Thus the following line is needed.

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

Alternatively, you could use Aspect Oriented Programming of some sort.

Following link provides an example using Spring AOP http://www.fiveminutes.eu/logging-with-spring-aop/

Upvotes: 0

Related Questions