创建WEB项目及其他配置在这里不进行描述,在今后的文章中会对WEB项目框架的使用做介绍. 这里将只描述如何在WEB项目中使用LOG4J(我用的服务器是tomcat6.0,IDE是myEclipse)
1、下载log4j.jar,添加到WEB-INF/lib中,并引入到项目的libraries中
2、在src下创建log4j.xml,添加如下配置
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<!-- 在项目中使用日志管理,将相应JAR包与XML文件放到相应目录下 -->
<log4j:configuration debug="false" xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="console" class="org.apache.log4j.ConsoleAppender">
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d [%t] %-5p (%c:%L) - %m%n" />
<param name="Encoding" value="GBK" />
</layout>
</appender>
<appender name="file" class="org.apache.log4j.RollingFileAppender">
<param name="threshold" value="info" />
<!-- 服务器安装目录下log文件的地址 -->
<param name="file" value="../logs/TestProject.log" />
<param name="maxFileSize" value="10MB" />
<param name="maxBackupIndex" value="5" />
<param name="append" value="true" />
<param name="Encoding" value="GBK" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%-d{yyyy-MM-dd HH:mm:ss.SSS} [%p]-[%c:%L] %m%n" />
</layout>
</appender>
<!-- This file appender is used to output aggregated performance statistics -->
<appender name="fileAppender" class="org.apache.log4j.FileAppender">
<param name="File" value="logs/perfStats.log" />
<param name="Append" value="false" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%m%n" />
</layout>
</appender>
<appender name="CoalescingStatistics" class="org.perf4j.log4j.AsyncCoalescingStatisticsAppender">
<param name="TimeSlice" value="60000" />
<appender-ref ref="fileAppender" />
</appender>
<logger name="org.perf4j.TimingLogger" additivity="false">
<level value="INFO" />
<appender-ref ref="CoalescingStatistics" />
</logger>
<logger name="org.apache.commons.beanutils" additivity="true">
<level value="ERROR" />
</logger>
<logger name="org.springframework.security" additivity="true">
<level value="ERROR" />
</logger>
<logger name="org.apache.commons.digester" additivity="true">
<level value="ERROR" />
</logger>
<logger name="org.springframework.flex.servlet" additivity="true">
<level value="WARN" />
</logger>
<root>
<level value="INFO" />
<appender-ref ref="console" />
<appender-ref ref="file" />
</root>
</log4j:configuration>
完成以上两步后,启动服务器就可看到初始化LOG的信息
在tomcat安装目录logs下创建TestProject.log,确保LOG信息能输出到该文件中
3、使用LOG4J
创建类似以下JAVA类
package com.hand.admin.service;
import org.apache.log4j.Logger;
public class UserService {
public String getMessage(){
final Logger logger = Logger.getLogger(UserService.class);
System.out.println("Excute UserService :"+"hello world!");
logger.info("Log output!");
return "Hello World";
}
}