web项目添加log4j
在web项目中添加log4j支持,文中使用maven搭建的SpringMVC环境,当然也可以使用其它的环境,这里主要介绍的是log4j的添加,其它的东西大家可以使用自己之前已经做好的web项目也是一样的:
1.使用maven添加所需要的jar包,当然也可以自己手动添加:
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>mavenWeb</groupId> <artifactId>mavenweb</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>mavenweb Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <spring.version>3.0.5.RELEASE</spring.version> <junit.version>4.8.2</junit.version> <netbeans.hint.deploy.server>Tomcat</netbeans.hint.deploy.server> <slfv5_common.version>1.0.9-beta</slfv5_common.version> <slf4j.version>1.6.6</slf4j.version> <log4j.version>1.2.17</log4j.version> <proxool.version>0.9.1</proxool.version> <mysql-client.version>5.1.21</mysql-client.version> <memcached-client.version>2.6.6</memcached-client.version> <sitemesh.version>2.4.2</sitemesh.version> <spring-json.version>1.9.9</spring-json.version> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>3.0.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>3.0.5.RELEASE</version> </dependency> <dependency> <groupId>org.apache.geronimo.specs</groupId> <artifactId>geronimo-servlet_2.5_spec</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> <scope>compile</scope> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4j.version}</version> <scope>compile</scope> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> <scope>compile</scope> </dependency> </dependencies> <build> <finalName>mavenweb</finalName> </build> </project>
完成之后会看到添加了如下jar包:
2.编写log4j.xml文件,其它log4j.xml的文件路径在发布到Tomcat的时候是在对应的目录是在E:\apache-tomcat-6.0.35\webapps\mavenweb\WEB-INF\classes中,所以在开发是大家要注意log4j.xml新建的位置:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE log4j:configuration PUBLIC "-//APACHE//DTD LOG4J 1.2//EN" "log4j.dtd"> <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"> <!-- Appenders --> <appender name="files" class="org.apache.log4j.DailyRollingFileAppender"> <param name="File" value="${catalina.base}/logs/mytest.log"/> <param name="DatePattern" value="'.'yyyy-MM-dd'.log'"/> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="[%d{yyyy-MM-dd HH:mm:ss SSS\} %-5p] [%t] %c{3\} - %m%n"/> </layout> </appender> <appender name="console" class="org.apache.log4j.ConsoleAppender"> <param name="Target" value="System.out" /> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="[%d{yyyy-MM-dd HH:mm:ss SSSS\} %-5p] [%t] %c{3\} - %m%n" /> </layout> </appender> <!-- Application Loggers --> <logger name="org.springframework.samples.mvc"> <level value="info" /> <appender-ref ref="files"/> </logger> <logger name="com.zxhz.maventest"> <level value="info" /> <appender-ref ref="files"/> </logger> <!-- 3rdparty Loggers --> <logger name="org.springframework.core"> <level value="info" /> <appender-ref ref="files"/> </logger> <logger name="org.springframework.beans"> <level value="info" /> <appender-ref ref="files"/> </logger> <logger name="org.springframework.context"> <level value="info" /> <appender-ref ref="files"/> </logger> <logger name="org.springframework.http"> <level value="debug" /> <appender-ref ref="files"/> </logger> <logger name="org.springframework.web"> <level value="debug" /> <appender-ref ref="files"/> </logger> <!-- Root Logger --> <root> <priority value="warn" /> <appender-ref ref="console" /> </root> </log4j:configuration>
这里就不说明每个属性了,需要了解的同学可以去找到一下别的文章。
web.xml文件:
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <servlet> <servlet-name>maven</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>maven</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
关于web.xml的写法,有一般情况下都会在在web.xml中加上以下代码:
<!--在web.xml中配置log4j的动态加载监听器--> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>classpath:log4j.properties</param-value> </context-param> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </listener>
但在上面的web.xml文件中并没有加入这些代码那是因为如果你的log4j.xml是放在classpath下,log4jConfigLocation是没有必要配置的,因为默认的 路劲就是classpath。spring的log4jConfigListener是用来监听log4j配置的变更的,如果设置了这个 监听器,则以后log4j的配置发生变化时,你不用重新编译打包发布项目。spring会自动加载变更后的 配置文件
maven-servlet.xml
<?xml version="1.0" encoding="UTF-8"?> <!-- Bean头部 --> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd"> <!-- 激活@Controller模式 --> <mvc:annotation-driven /> <!-- 对包中的所有类进行扫描,以完成Bean创建和自动依赖注入的功能 需要更改 --> <context:component-scan base-package="com.zxhz" /> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" /> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix"> <value>/WEB-INF/jsp/</value> </property> <property name="suffix"> <value>.jsp</value> </property> </bean> </beans>
3.在相对应的类中定义Loger以下有两个类以及页面文件:
LoginController.java
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; @Controller public class LoginController { /*** * 在这里并没有去加载log4j.xml,也没有在web.xml * 文件中设置log4j.xml,这是因为Spring框架默认情况下会自动地去 * 找classes目录下面的log4j.xml文件并加载它 */ private static Logger log = LoggerFactory.getLogger(LoginController.class); @RequestMapping(value = "login") public ModelAndView login(HttpServletRequest request, HttpServletResponse response, LoginForm command) { String username = command.getUsername(); ModelAndView mv = new ModelAndView("/index/index", "command", "LOGIN SUCCESS, " + username); log.info("test,test,test,123456789"); return mv; } }
LoginForm.java
public class LoginForm { private String username; private String password; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
index.jsp
<html> <body> <% request.getRequestDispatcher("/WEB-INF/jsp/login/login.jsp") .forward(request, response); %> </body> </html>
WEB-INF/jsp/index/index.jsp
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Insert title here</title> </head> <body>${command} </body> </html>
WEB-INF/jsp/index/login.jsp
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Insert title here</title> </head> <body> <div> <form action="login" method="get"> <input type="text" name="username"> <input type="submit" value="SUBMIT"> </form> </div> </body> </html>
4.在这些都完成后就可以启动服务器在浏览器中访问路径,这时候可以在后台看到输出的log
[2013-03-12 02:20:53 671 INFO ] [http-80-1] zxhz.maventest.LoginController - test,test,test,123456789
并且在Tomcat安装目录下的logs目录中找到对应的mytest.log文件。
5.目录结构如下: