开发者

Where to declare log4j in servlets and filters?

开发者 https://www.devze.com 2023-02-22 10:10 出处:网络
I am confusing when I try log the process using log4j, I don\'t know where to put the logger. Now I\'ve put the logger in the servlet and declared it as public static so that everyone can use 开发者_如

I am confusing when I try log the process using log4j, I don't know where to put the logger. Now I've put the logger in the servlet and declared it as public static so that everyone can use 开发者_如何学运维it. My filter use the logger too. But I am not sure if the servlet is destroy, will the logger destroyed too?

Another question, in my understanding, filter is before servlet, and as I create the logger in the servlet, in the very beginning, the filter should not be able to use the logger, however, as I let the filter log the process, there are no some kind of exception like "logger does not exist", why?

What is the best place for the logger? And should it be static, that is, multiple class can share one logger? I would like to place the logs of filter and servlet together.


Create a private static final Logger for each class. For example, write following line in your servlet class:

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

and following line in your filter class:

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

Notice the different values passed as parameters in getLogger() method. The logger should be private static so that multiple instances of same class can use it. This way you can control output from your application class-wise. For example, if you want to see output from all instances of YourServletClassName only (although only one instance of a Servlet class is created usually, which is re-used for handling every request), you can write following lines in your log4j.properties:

log4j.logger.your.package.YourServletClassName=TRACE
log4j.logger.your.package.YourFilterClassName=OFF

This way, logs from YourServletClassName will be shown only and nothing will shown from YourFilterClassName. Hope it helps.


You should be defining a seperate logger in each of your classes

static org.apache.log4j.Logger logger = Logger.getLogger(MyClass.class);

This way your log file is clearly arranged and you can have correct categories in your configuration file.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号