1、依赖包
commons-logging-1.1.3.jar、log4j-1.2.15.jar
2、配置Web.xml
1 <context-param> 2 <param-name>log4jConfigLocation</param-name> 3 <param-value>/WEB-INF/log4j.properties</param-value> 4 </context-param> 5 <listener> 6 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 7 </listener>
3、配置log4j.properties属性文件
1 ################ FATAL, ERROR, WARN, INFO, DEBUG 2 log4j.rootLogger=WARN,stdout,D,E 3 4 ### stdout ### 5 log4j.appender.stdout=org.apache.log4j.ConsoleAppender 6 log4j.appender.stdout.Target=System.out 7 log4j.appender.stdout.layout=org.apache.log4j.PatternLayout 8 log4j.appender.stdout.layout.ConversionPattern= %d{ABSOLUTE} %5p %c{1}:%L - %m%n 9 10 ### logFile ### 11 ### save error to another file ### 12 log4j.appender.D=org.apache.log4j.DailyRollingFileAppender 13 log4j.appender.D.File=D:/logs/test-error.log 14 log4j.appender.D.Append=true 15 #error only in this file 16 log4j.appender.D.Threshold =WARN 17 log4j.appender.D.layout=org.apache.log4j.PatternLayout 18 log4j.appender.D.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} [%t:%r] - [%p] %m%n
4、全局异常处理,servlet-config.xml配置
1 <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> 2 <property name="exceptionMappings"> 3 <props> 4 <prop key="java.lang.Exception">errors/error</prop> 5 <prop key="java.lang.Throwable">errors/err</prop> 6 </props> 7 </property> 8 <property name="statusCodes"> 9 <props> 10 <prop key="errors/error">500</prop> 11 <prop key="errors/404">404</prop> 12 </props> 13 </property> 14 <!-- 设置日志输出级别,不定义则默认不输出警告等错误日志信息 --> 15 <property name="warnLogCategory" value="WARN"></property> 16 <!-- 默认错误页面,当找不到上面mappings中指定的异常对应视图时,使用本默认配置 --> 17 <property name="defaultErrorView" value="errors/error"></property> 18 <!-- 默认HTTP状态码 --> 19 <property name="defaultStatusCode" value="500"></property> 20 </bean> 21 <!-- 全局异常配置 end -->
5、代码日志写入
1 private final Log logger = LogFactory.getLog(SimplerController.class); 2 3 logger.warn(" logger"); 4 logger.error("~~info~~");
6、参考
时间: 2024-11-07 10:50:08