log4j
一、log4j
日志是应用软件中不可缺少的部分,Apache开源的log4j是一个功能强大的日志组件,提供了方便的日志记录功能。
下载地址:http://jakarta.apache.org/log4j
(一) 配置文件
Logger类:完成日志记录,设置日志优先级
OFF(关闭)、FATAL(严重)、ERROR(错误)、WARN(警告)、INFO(信息)、DEBUG(调试)、ALL(所有)、或者自己定义级别
log4j.rootLogger=${logger.level},RUNTIME
log4j.logger.INTERFACE=${logger.level},INTERFACE
log4j.additivity.INTERFACE=false #是否继承父Logger的输出源,默认继承
Appender类:决定日志去向,终端、DB、硬盘
log4j.appender.appenderName = org.apache.log4j.ConsoleAppender
org.apache.log4j.ConsoleAppender #控制台
org.apache.log4j.FileAppender #文件
org.apache.log4j.DailyRollingFileAppender #每天产生一个日志文件
org.apache.log4j.RollingFileAppender #文件大小到达指定尺寸的时候产生一个新的文件
org.apache.log4j.WriterAppender #将日志信息以流格式发送到任意指定的地方
Layout类:决定日志输出格式,例如包含当前线程、行号、时间
log4j.appender.appenderName.layout = fully.qualified.name.of.layout.class
org.apache.log4j.HTMLLayout #以HTML表格形式布局
org.apache.log4j.PatternLayout #可以灵活地指定布局模式
org.apache.log4j.SimpleLayout #包含日志信息的级别和信息字符串
org.apache.log4j.TTCCLayout #包含日志产生的时间、线程、类别等等信息
(二) java代码
1. 日志记录器
public static Logger getLogger(String name); //Logger.getLogger ( ServerWithLog4j.class.getName () ) //LoggerFactory.getLogger(this.getClass()) private static Logger logger = LoggerFactory.getLogger("INTERFACE");
2. 读取配置文件
//当获取了日志记录器后,第二步读取配置文件 BasicConfigurator.configure()//自动快速地使用缺省Log4j环境。 PropertyConfigurator.configure(String configFilename)//读取properties配置文件。 DOMConfigurator.configure(String filename)//读取XML形式的配置文件。
3. 插入记录信息
//当完成以上两个步骤后,就可以使用不同优先级的日志记录语句插入到输出源 Logger.debug (Object message); Logger.info (Object message); Logger.warn (Object message); Logger.error (Object message);
二、log4j.properties
### 设置###
log4j.rootLogger = debug,stdout,D,E
### 输出信息到控制抬 ###
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n
### 输出DEBUG 级别以上的日志到=E://logs/error.log ###
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = E://logs/log.log
log4j.appender.D.Append = true
log4j.appender.D.Threshold = DEBUG
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
### 输出ERROR 级别以上的日志到=E://logs/error.log ###
log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
log4j.appender.E.File =E://logs/error.log
log4j.appender.E.Append = true
log4j.appender.E.Threshold = ERROR
log4j.appender.E.layout = org.apache.log4j.PatternLayout
log4j.appender.E.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
三、java工程
1. 导入log4的jar包
2. log4j.properties
3. java代码中记录日志
public class Test { //日志记录器 private static Logger logger = Logger.getLogger(Test.class); public static void main(String[] args) { // 记录debug级别的信息 logger.debug("This is debug message."); // 记录info级别的信息 logger.info("This is info message."); // 记录error级别的信息 logger.error("This is error message."); } }
4. 输出结果
首先是控制台的信息
再来看输出文件的日志
四、web工程
在J2EE应用中使用log4j,必须先在启动服务时加载log4j的配置文件进行初始化,可以在web.xml中进行配置。
1. 导入log4j的jar
2. log4j.properties
3. web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>LogLearning</display-name> <servlet> <servlet-name>Log4JTestServlet</servlet-name> <servlet-class>com.mucfc.Log4JTestServlet</servlet-class> </servlet> <!--用来启动 log4jConfigLocation的servlet --> <servlet> <servlet-name>Log4JInitServlet</servlet-name> <servlet-class>com.mucfc.Log4JInitServlet</servlet-class> <init-param> <param-name>log4j-properties-location</param-name> <param-value>/WEB-INF/classes/log4j.properties</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>Log4JTestServlet</servlet-name> <url-pattern>/test</url-pattern> </servlet-mapping> </web-app>
4. 初始化servlet
//web容器一来就初始化的Log4jInitServlet.java @WebServlet("/Log4JInitServlet") public class Log4JInitServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public Log4JInitServlet() { super(); } /** * @see Servlet#init(ServletConfig) */ public void init(ServletConfig config) throws ServletException { System.out.println("Log4JInitServlet 正在初始化 log4j日志设置信息"); String log4jLocation = config.getInitParameter("log4j-properties-location"); ServletContext sc = config.getServletContext(); if (log4jLocation == null) { System.err.println("没有 log4j-properties初始化的文件, 所以使用 BasicConfigurator初始化"); BasicConfigurator.configure(); } else { String webAppPath = sc.getRealPath("/"); String log4jProp = webAppPath + log4jLocation; File yoMamaYesThisSaysYoMama = new File(log4jProp); if (yoMamaYesThisSaysYoMama.exists()) { System.out.println("使用: " + log4jProp+"初始化日志设置信息"); PropertyConfigurator.configure(log4jProp); } else { System.err.println("*** " + log4jProp + " 文件没有找到, 所以使用 BasicConfigurator初始化"); BasicConfigurator.configure(); } } super.init(config); } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws Exception { // TODO Auto-generated method stub } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws Exception { // TODO Auto-generated method stub } }
5. 调用日志
//调用日志Log4JTestServlet,java /** * Servlet implementation class Log4JTestServlet */ @WebServlet("/Log4JTestServlet") public class Log4JTestServlet extends HttpServlet { private static final long serialVersionUID = 1L; private static Logger logger = Logger.getLogger(Log4JTestServlet.class); /** * @see HttpServlet#HttpServlet() */ public Log4JTestServlet() { super(); // TODO Auto-generated constructor stub } /** * @see Servlet#init(ServletConfig) */ public void init(ServletConfig config) throws ServletException { // TODO Auto-generated method stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws Exception { // 记录debug级别的信息 logger.debug("This is debug message."); // 记录info级别的信息 logger.info("This is info message."); // 记录error级别的信息 logger.error("This is error message."); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws Exception { doGet(request,response); } }
五、spring工程
日志跟随spring启动而启动
1. web + spring工程
使用spring启动来初始化log4j配置
2. log4j.properties
3. web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>LogLearning</display-name> <servlet> <servlet-name>Log4JTestServlet</servlet-name> <servlet-class>com.mucfc.Log4JTestServlet</servlet-class> </servlet> <!--用来启动 log4jConfigLocation的servlet --> <!-- <servlet> <servlet-name>Log4JInitServlet</servlet-name> <servlet-class>com.mucfc.Log4JInitServlet</servlet-class> <init-param> <param-name>log4j-properties-location</param-name> <param-value>/WEB-INF/classes/log4j.properties</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet>--> <servlet-mapping> <servlet-name>Log4JTestServlet</servlet-name> <url-pattern>/test</url-pattern> </servlet-mapping> <!-- Spring 容器加载 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <!-- 设置根目录 --> <context-param> <param-name>webAppRootKey</param-name> <param-value>webapp.root</param-value> </context-param> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>/WEB-INF/classes/log4j.properties</param-value> </context-param> <!-- 3000表示 开一条watchdog线程每60秒扫描一下配置文件的变化;这样便于日志存放位置的改变 --> <context-param> <param-name>log4jRefreshInterval</param-name> <param-value>3000</param-value> </context-param> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </listener> </web-app>
4. applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd"> </beans>