views:

82

answers:

3

Hi Guys,

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..

A: 

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

Chino
+1  A: 

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");
Roman
but I want logs to be written onto one file... So, I'll have to add file handlers all the time...
Sunny
Your logger configuration file goes in WEB-INF/classes/log4j.xml. That file tells log4j which file you want to record your logs in.Also, I think it's slightly better to say `getLogger(UserCounterServlet.class);` because then if you make a typo, your IDE will let you know.
John
@John: about UserCounterServlet.class - you're right for sure, will correct.
Roman
A: 

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)

Alexey Sviridov