a Sample for Log4j

王朝java/jsp·作者佚名  2006-01-09
窄屏简体版  字體: |||超大  

1.Some tools

Tomcat

Log4j_1.2.9 http://mirrors.xtria.com/apache/logging/log4j/1.2.9/logging-log4j-1.2.9.zip

2. four files

a. web.xml

add following code to web.xml

<servlet>

<servlet-name>log4j-init</servlet-name>

<servlet-class>com.legendinfo.log.Log4jInit</servlet-class>

<init-param>

<param-name>log4j-init-file</param-name>

<param-value>WEB-INF/classes/log4j.property</param-value>

</init-param>

<load-on-startup>1</load-on-startup>

</servlet>

b.create a special servlet for log4j initialazation

save the file in the web-info/classes folder

package com.legendinfo.log;

import org.apache.log4j.PropertyConfigurator;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import java.io.PrintWriter;

import java.io.IOException;

public class Log4jInit extends HttpServlet {

public void init() {

String prefix = getServletContext().getRealPath("/");

String file = getInitParameter("log4j-init-file");

// if the log4j-init-file is not set, then no point in trying

if(file != null) {

PropertyConfigurator.configure(prefix+file);

System.out.println("Init Log4j success!");

}

}

public void doGet(HttpServletRequest req, HttpServletResponse res) {

}

}

c.create a log4j.property file that define the log4j properties

the property file is setting in web.xml

a sample property file as following

log4j.rootLogger=INFO, A1 ,R

log4j.appender.A1=org.apache.log4j.ConsoleAppender

log4j.appender.A1.layout=org.apache.log4j.PatternLayout

log4j.appender.A1.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} [%c]-[%p] %m%n

log4j.appender.R=org.apache.log4j.RollingFileAppender

log4j.appender.R.File=../logs/log4j.log

log4j.appender.R.MaxFileSize=100KB

log4j.appender.R.MaxBackupIndex=1

log4j.appender.R.layout=org.apache.log4j.TTCCLayout

d.a test Jsp page

testLog.jsp:

<%@ page import="org.apache.log4j.*"%>

<html>

<body>

<%

//log4j.appender.appenderName = WEB-INF/classes/log4j.log

Logger logger = Logger.getLogger("com.legendinfo");

logger.setLevel(Level.INFO);

Logger barlogger = Logger.getLogger("com.legendinfo.log");

logger.warn("Low fuel level.");

logger.debug("Starting search for nearest gas station.");

barlogger.info("Located nearest gas station.");

barlogger.debug("Exiting gas station search");

%>

</body>

</html>

3. resault

after you startup your tomcat , you can see the success log “Init Log4j success!“

and you can look the testLog.jsp then the logs will be found in the tomcat log file and log/log4j.log file

4.some feedback please send to http://blog.csdn.net/legendinfo or jiujiul@126.com

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航