首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > Web前端 >

How do I initialize Log4J in a web application

2012-09-03 
How do I initialize Log4J in a web application?In other tutorials, we saw that log4j needs to be in

How do I initialize Log4J in a web application?

In other tutorials, we saw that log4j needs to be initialized in order to be used, and we saw how log4j can be initialized with a BasicConfigurator and initialized with a PropertyConfigurator. This typically occurs when an application starts up. In a web application, we'd also like log4j to start up when the application starts up. One straightforward way of doing this is to put this log4j initialization in a servletW, and specify for the servlet to start up when the application starts up.

Here is a web application project to illustrate this. It contains the log4j jarW file in its build path, a log4j.properties file, a web.xmlW file, a log4j initialization servlet, and a test servlet to try out our log4j initialization.

How do I initialize Log4J in a web application

Let's start by examining our web.xml file. It contains references to our two servletsW, Log4JTestServlet and Log4JInitServlet. Log4JTestServlet gets mapped to /test so that it can be hit via a browser. The Log4JInitServlet starts up when the web application starts up because of the <load-on-startup> tag. Notice that it has an init-param and an init-value. This value gets passed to the servlet and specifies the location of our log4j.properties file.

web.xml
);BasicConfigurator.configure();}}

If we now check our console window, we can see the logging messages that were output in the doGet() method of our test servlet. The output is formatted as we specified in the log4j.properties file. Notice that the log.debug() message in doGet() isn't displayed to the console, since our log4j.properties file specified that the log level is INFO.

How do I initialize Log4J in a web application

Initializing log4j via a servlet that loads on web application start-up is a handy technique for initializing log4j.

热点排行