Sunny
Sunny

Reputation: 286

Java Logger with Servlets

I am using a wrapper class A which initializes the java.util.logger

static class A {

    public static Logger logger;

    public static void init(){

    logger = Logger.getLogger("test");

}

Now, everywhere in my program I call A.init() and then logger.log("Message+uniqid"). But recently I moved to HTTP servlets and I am having problems.

Basically, If a app is already running and the logger is logging... and someone else runs the app again, the logger from the previous instance stops and starts logging for the second one. Can anyone have a solution to how I should go about fixing this static variable issue?

I can pass the logger into all constructor classes but thats really tedious. Any better solution would be appreciated..

Upvotes: 1

Views: 11667

Answers (3)

Roman
Roman

Reputation: 66156

You don't need to initialize your logger multiple times.

Actually, you don't even need to do it manually because you can create a properties-file with configuration information and put it to the certain directory in the way that this file will be deployed to WEB-INF/classes folder in your application server.

In the configuration file (properties-file) you can define different ways of writing logs. Then when you want to write log from some servlet, for example UserCounterServlet, you should do:

private static final Logger logger = Logger.getLogger (UserCounterServlet.class);
...
logger.info("some info");

Upvotes: 3

Alexey Sviridov
Alexey Sviridov

Reputation: 3490

If you want really good logging solution in servlets, don't use a static logger (even if you know about some famous servlet-based projects use this way of logging). Use right logging solution developed with web app in mind (for example LogBack - advance of log4j, or so on)

Upvotes: 1

Chino
Chino

Reputation: 821

Yes never use static on a webapplication and what user177883 said use log4j it is a good solution for logging so why bother to write it from scratch

Upvotes: 0

Related Questions