java 中使用log4j
一、控制台使用
1、导入log4j包到工程中
2、配置:
log4j.rootLogger=DEBUG,console,R log4j.appender.console=org.apache.log4j.ConsoleAppender log4j.appender.console.threshold=INFO log4j.appender.console.layout=org.apache.log4j.PatternLayout log4j.appender.R=org.apache.log4j.RollingFileAppender log4j.appender.R.Append=true log4j.appender.R.File=main.log log4j.appender.R.Threshold=DEBUG log4j.appender.R.layout=org.apache.log4j.PatternLayout log4j.appender.R.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} [%5p] - %c -%F(%L) -%m%n log4j.appender.R.MaxFileSize=20MB log4j.org.springframework.web=DEBUG
工程结构如图:
3、使用:
public class Main { static org.apache.log4j.Logger logger=org.apache.log4j.LogManager.getLogger(Main.class); public static void main(String[] args) { logger.info("main"); System.out.println("Hello World!"); } }
二、Java Web中使用
1、导入log4j包到工程中
2、log4j配置(同上)
3、在Web.xml中配置l加载og4j
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/applicationContext.xml,/WEB-INF/dispatcher-servlet.xml</param-value> </context-param> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>/WEB-INF/log4j.properties</param-value> </context-param> <context-param> <param-name>log4jRefreshInterval</param-name> <param-value>60000</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </listener> <servlet> <servlet-name>dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>*.form</url-pattern> </servlet-mapping> </web-app>
4、使用同上