日志是应用软件中不可缺少的部分,Apache的开源项目log4j是一个功能强大的日志组件,提供方便的日志记录。
1.maven配置
<dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency>
2.web.xml配置
<context-param> <param-name>log4jConfigLocation</param-name> <param-value>classpath:/log4j/log4j.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </listener>
3.log4j.xml配置
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"> <log4j:configuration xmlns:log4j='http://jakarta.apache.org/log4j/' > <appender name="myConsole" class="org.apache.log4j.ConsoleAppender"> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="[%d{dd HH:mm:ss,SSS} %-5p] [%t] %c{2} - %m%n" /> </layout> <!-- 过滤器设置输出的级别 --> <filter class="org.apache.log4j.varia.LevelRangeFilter"> <param name="levelMin" value="debug" /> <param name="levelMax" value="warn" /> <param name="AcceptOnMatch" value="true" /> </filter> </appender> <appender name="myFile" class="org.apache.log4j.RollingFileAppender"> <param name="File" value="${catalina.home}/logs/tomcat_output_errorInfo.log" /><!-- 设置日志输出文件名 errorInfo--> <!-- 设置是否在重新启动服务时,在原有日志的基础添加新日志 --> <param name="Append" value="false" /> <param name="MaxBackupIndex" value="10" /> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%p (%c:%L)- %m%n" /> </layout> </appender> <appender name="activexAppender" class="org.apache.log4j.DailyRollingFileAppender"> <param name="File" value="${catalina.home}/logs/tomcat_output_sqlInfo.log" /><!-- 设置日志输出文件名 sqlInfo--> <param name="DatePattern" value="'.'yyyy-MM-dd'.log'" /> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="[%d{MMdd HH:mm:ss SSS} %-5p] [%t] %c{3} - %m%n" /> </layout> </appender> <!-- 指定logger的设置,additivity指示是否遵循缺省的继承机制--> <logger name="com.online" additivity="false"> <appender-ref ref="activexAppender" /> </logger> <!-- 根logger的设置--> <root> <priority value ="debug"/> <appender-ref ref="myConsole"/> <appender-ref ref="myFile"/> </root> </log4j:configuration>
4.tomcat logs 查看日志