步骤:
1.导入log4j.jar
2.配置log4j.properties
#配置级别Logger(FATAL,ERROR,WARN,INFO,DEBUG) #log4j.rootLogger = [level],appenderName1,appenderName2,... log4j.rootLogger = debug , stdout #配置日志输出目的地Appender(ConsoleAppender,FileAppender,DailyRollingFileAppender,RollingFileAppender,WriterAppender) #log4j.appender.appenderName = fully.qualified.of.appender.class #输出到控制台 log4j.appender.stdout = org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target = System.out #配置日志输出格式Layout(HTMLLayout,PatternLayout,SimpleLayout,TTCCLayout) #log4j.appender.appenderName.layout = fully.qualified.name.of.layout.class log4j.appender.stdout.layout = org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern = %d{ABSOLUTE} %5p %c{1}:%L - %m%n #打印参数: #%m 输出代码中指定的消息 #%p 输出优先级,即DEBUG,INFO,WARN,ERROR,FATAL #%r 输出自应用启动到输出该log信息耗费的毫秒数 #%c 输出所属的类目,通常就是所在类的全名 #%t 输出产生该日志事件的线程名 #%n 输出一个回车换行符,Windows平台为“/r/n”,Unix平台为“/n” #%d 输出日志时间点的日期或时间,默认格式为ISO8601,也可以在其后指定格式,比如:%d{yyy MMM dd HH:mm:ss , SSS},输出类似:2002年10月18日 22 : 10 : 28 , 921 #%l 输出日志事件的发生位置,包括类目名、发生的线程,以及在代码中的行数。举例:Testlog4.main(TestLog4.java: 10 )
3.web.xml中加载配置
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <!-- spring --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> <description>spring</description> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- log4j --> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>classpath:properties/log4j.properties</param-value> </context-param> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </listener> <!-- filter --> <filter> <filter-name>RouteFilter</filter-name> <filter-class>com.binf.springtest.filter.RouteFilter</filter-class> </filter> <filter-mapping> <filter-name>RouteFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- springmvc --> <servlet> <servlet-name>springMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springMVC.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>springMVC</servlet-name> <!-- 不能拦截*.jsp文件,因为这样返回的jsp还是会被拦截,报404,默认不拦截*.jsp,并且不能直接访问WEB-INF下的页面 --> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
4.测试: