Java学习-007-Log4J 日志记录配置文件详解及实例源代码

时间:2022-03-16 17:47:21

此文主要讲述在初学 Java 时,常用的 Log4J 日志记录配置文件详解及实例源代码整理。希望能对初学 Java 编程的亲们有所帮助。若有不足之处,敬请大神指正,不胜感激!源代码测试通过日期为:2015-1-30 13:54:02,请知悉。

所需的 jar 包下载链接为:http://yunpan.cn/cKE56sxqtQCfP  访问密码 63d8

有关 Log4J 日志文件中日志级别及文件配置的详细情况,在 Log4J 的配置文件(xml、properties)中有详细的介绍,敬请参阅!

  • xml 配置文件
Java学习-007-Log4J 日志记录配置文件详解及实例源代码Java学习-007-Log4J 日志记录配置文件详解及实例源代码
  1 <?xml version="1.0" encoding="UTF-8" ?>  
2 <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
3 <!-- ========================== 日志输出等级 ================================ -->
4 <!-- OFF:最高等级, 用于关闭所有日志记录 -->
5 <!-- FATAL:输出严重级别的消息 -->
6 <!-- ERROR:输出错误级别的消息 -->
7 <!-- WARN:输出警告级别的消息 -->
8 <!-- INFO:输出信息级别的消息 -->
9 <!-- DEBUG:输出调试级别的消息 -->
10 <!-- TRACE:输出跟踪级别的消息 -->
11 <!-- ALL:最低等级, 用于打开所有日志记录 -->
12 <!-- 只有当输出日期的级别大于或等于为日志配置器配置的日志级别时, 这个方法才会执行. 指定日志器的日志级别, 不同的日志器会实现不同的日志输出方案 -->
13
14 <!-- ========================== 自定义输出格式说明 ================================ -->
15 <!-- %p 输出优先级,即DEBUG,INFO,WARN,ERROR,FATAL -->
16 <!-- %r 输出自应用启动到输出该log信息耗费的毫秒数 -->
17 <!-- %c 输出所属的类目,通常就是所在类的全名 -->
18 <!-- %t 输出产生该日志事件的线程名 -->
19 <!-- %n 输出一个回车换行符,Windows平台为“\r\n”,Unix平台为“\n” -->
20 <!-- %d 输出日志时间点的日期或时间,默认格式为ISO8601,也可以在其后指定格式,比如:%d{yyy MMM dd HH:mm:ss,SSS},输出类似:2002年10月18日 22:10:28,921 -->
21 <!-- %l 输出日志事件的发生位置,包括类目名、发生的线程,以及在代码中的行数。举例:Testlog4.main(TestLog4.java:10) -->
22 <!-- ========================================================================== -->
23
24 <!-- ========================== 输出方式说明================================ -->
25 <!-- Log4j提供的appender有以下几种: -->
26 <!-- org.apache.log4j.ConsoleAppender(控制台), -->
27 <!-- org.apache.log4j.FileAppender(文件), -->
28 <!-- org.apache.log4j.DailyRollingFileAppender(每天产生一个日志文件), -->
29 <!-- org.apache.log4j.RollingFileAppender(文件大小到达指定尺寸的时候产生一个新的文件), -->
30 <!-- org.apache.log4j.WriterAppender(将日志信息以流格式发送到任意指定的地方) -->
31 <!-- ========================================================================== -->
32
33 <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
34 <!-- 系统运行日志 {TRACE, ERROR} -->
35 <appender name="InfoConsole" class="org.apache.log4j.ConsoleAppender">
36 <!-- 不进行缓存, 直接输出 -->
37 <param name="ImmediateFlush" value="true"></param>
38 <!-- 指定输出控制台, 默认情况下是 System.out -->
39 <param name="Target" value="System.err"></param>
40 <!-- 设置输出文件项目和格式 -->
41 <layout class="org.apache.log4j.PatternLayout">
42 <param name="ConversionPattern" value="{InfoConsole} - %d - %-5p - [%F] [%t] [%c:%L] - %m%n" />
43 </layout>
44
45 <!--限制输出级别 -->
46 <filter class="org.apache.log4j.varia.LevelRangeFilter">
47 <param name="LevelMax" value="ERROR" ></param>
48 <param name="LevelMin" value="TRACE" ></param>
49 </filter>
50 </appender>
51
52 <!-- 系统运行的错误日志 {ERROR, FATAL}, 单一 -->
53 <appender name="SysRunningErrorLog" class="org.apache.log4j.FileAppender">
54 <!-- 设置File参数:日志输出文件名 -->
55 <param name="File" value="logs/SysRunningErrorLog.log" ></param>
56 <!-- 设置在重新启动服务时,在原有日志的基础添加新日志 -->
57 <param name="Append" value="true" ></param>
58
59 <layout class="org.apache.log4j.PatternLayout">
60 <param name="ConversionPattern" value="{SysRunningErrorLog} - %d - %-5p - [%F] [%t] [%c:%L] - %m%n" ></param>
61 </layout>
62
63 <filter class="org.apache.log4j.varia.LevelRangeFilter">
64 <param name="LevelMax" value="FATAL" ></param>
65 <param name="LevelMin" value="ERROR" ></param>
66 </filter>
67 </appender>
68
69 <!-- 系统运行的调试日志 {DEBUG}, 大小-->
70 <appender name="SysRunningDebugLog" class="org.apache.log4j.RollingFileAppender">
71 <param name="File" value="logs/SysRunningDebugLog.log" ></param>
72 <param name="Append" value="true" ></param>
73 <!-- 设置文件大小 -->
74 <param name="MaxFileSize" value="5MB" ></param>
75 <!-- 设置文件备份 -->
76 <param name="MaxBackupIndex" value="21" ></param>
77 <layout class="org.apache.log4j.PatternLayout">
78 <param name="ConversionPattern" value="{SysRunningDebugLog} - %d - %-5p - [%F] [%t] [%c:%L] - %m%n" ></param>
79 </layout>
80
81 <filter class="org.apache.log4j.varia.LevelRangeFilter">
82 <param name="LevelMax" value="DEBUG" ></param>
83 <param name="LevelMin" value="DEBUG" ></param>
84 </filter>
85 </appender>
86
87 <!-- 系统运行的用户日志 {INFO, WARN}, 每天, LOG -->
88 <appender name="SysRunCustUseLog" class="org.apache.log4j.DailyRollingFileAppender">
89 <param name="File" value="logs/SysRunCustUseLog.log" ></param>
90 <param name="Append" value="true" ></param>
91 <param name="ImmediateFlush" value="true" ></param>
92 <param name="DatePattern" value="'-'yyyyMMdd'.log'" ></param>
93 <layout class="org.apache.log4j.PatternLayout">
94 <param name="ConversionPattern" value="{SysRunCustUseLog} - %d - %-5p - [%F] [%t] [%c:%L] - %m%n" ></param>
95 </layout>
96
97 <filter class="org.apache.log4j.varia.LevelRangeFilter">
98 <param name="LevelMax" value="WARN" ></param>
99 <param name="LevelMin" value="INFO" ></param>
100 </filter>
101 </appender>
102
103 <!-- 系统运行的用户日志 {INFO, WARN}, 每天, HTM -->
104 <appender name="SysRunCustUseLogHtm" class="org.apache.log4j.DailyRollingFileAppender">
105 <param name="File" value="logs/SysRunCustUseLogHtm.html" ></param>
106 <param name="Append" value="true" ></param>
107 <param name="ImmediateFlush" value="true" ></param>
108 <param name="DatePattern" value="'-'yyyyMMdd'.html'" ></param>
109 <layout class="org.apache.log4j.HTMLLayout">
110 <param name="Title" value="Logs info for the current running system from Log4J Message"></param>
111 </layout>
112
113 <filter class="org.apache.log4j.varia.LevelRangeFilter">
114 <param name="LevelMax" value="WARN" ></param>
115 <param name="LevelMin" value="INFO" ></param>
116 </filter>
117 </appender>
118
119 <!-- 系统运行的用户日志 {INFO, WARN} 每天, XML -->
120 <appender name="SysRunCustUseLogXml" class="org.apache.log4j.DailyRollingFileAppender">
121 <param name="File" value="logs/SysRunCustUseLogXml.xml"></param>
122 <param name="DatePattern" value="'-'yyyyMMdd'.xml'"></param>
123 <layout class="org.apache.log4j.xml.XMLLayout"></layout>
124
125 <filter class="org.apache.log4j.varia.LevelRangeFilter">
126 <param name="LevelMax" value="WARN"></param>
127 <param name="LevelMin" value="INFO"></param>
128 </filter>
129 </appender>
130
131 <!-- 系统运行的所有日志 {TRACE, FATAL} -->
132 <!-- MySQL, sqlserver JDBC 连接实例
133 <param name="URL" value="jdbc:mysql://127.0.0.1:3306/test" ></param>
134 <param name="driver" value="com.mysql.jdbc.Driver" ></param>
135 <param name="URL" value="jdbc:microsoft:sqlserver://127.0.0.1:1433;DatabaseName=Aaron" ></param>
136 <param name="driver" value="com.microsoft.jdbc.sqlserver.SQLServerDriver" ></param>
137 -->
138 <!--
139 <appender name="SysRunInfoDB" class="org.apache.log4j.jdbc.JDBCAppender">
140 <param name="URL" value="jdbc:oracle:thin:@127.0.0.1:1521:aaron" ></param>
141 <param name="driver" value="oracle.jdbc.driver.OracleDriver" ></param>
142 <param name="user" value="hr" ></param>
143 <param name="password" value="hr" ></param>
144 <layout class="org.apache.log4j.PatternLayout">
145 <param name="ConversionPattern" value="INSERT INTO sysRunInfoLog4J (appenderName, logTime, infoLevel, fileName, threadName, className, lineNumber, infoMsg) VALUES ('SysRunInfoDB', '%d', '%p', '%F', '%t', '%c', '%L', '%m')"></param>
146 </layout>
147
148 <filter class="org.apache.log4j.varia.LevelRangeFilter">
149 <param name="LevelMax" value="FATAL"></param>
150 <param name="LevelMin" value="TRACE"></param>
151 </filter>
152 </appender>
153 -->
154
155 <!-- 发邮件(只有ERROR时才会发送!) -->
156 <!-- <appender name="adMail" class="org.apache.log4j.net.SMTPAppender">
157 <param name="threshold" value="debug"></param>
158 <param name="BufferSize" value="512"></param>
159 <param name="From" value="test@163.com"></param>
160 <param name="SMTPHost" value="smtp.163.com"></param>
161 <param name="Subject" value="Logs info for the current running system from Log4J Message"></param>
162 <param name="To" value="test@163.com"></param>
163 <param name="SMTPUsername" value="test"></param>
164 <param name="SMTPPassword" value="test"></param>
165 <layout class="org.apache.log4j.PatternLayout">
166 <param name="ConversionPattern" value="{adMail} - %d - %-5p - [%F] [%t] [%c:%L] - %m%n"></param>
167 </layout>
168
169 <filter class="org.apache.log4j.varia.LevelRangeFilter">
170 <param name="LevelMax" value="FATAL"></param>
171 <param name="LevelMin" value="ERROR"></param>
172 </filter>
173 </appender> -->
174
175 <!--- 异步测试,当日志达到缓存区大小时候执行所包的appender -->
176 <appender name="ASYNC" class="org.apache.log4j.AsyncAppender">
177 <param name="BufferSize" value="256"></param>
178 <appender-ref ref="SysRunningDebugLog"></appender-ref>
179 <appender-ref ref="SysRunCustUseLog"></appender-ref>
180 <appender-ref ref="SysRunCustUseLogHtm"></appender-ref>
181 <appender-ref ref="SysRunCustUseLogXml"></appender-ref>
182 </appender>
183
184 <!--通过<logger>的定义可以将各个包中的类日志输出到不同的日志文件中 -->
185 <!--<logger name="test.log4j" additivity="false">
186 <level value="INFO"></level>
187 <appender-ref ref="InfoConsole"></appender-ref>
188 <appender-ref ref="adDatabase"></appender-ref>
189 <appender-ref ref="SysRunningErrorLog"></appender-ref>
190 </logger>-->
191
192 <!--通过<category></category>的定义可以将各个包中的类日志输出到不同的日志文件中 -->
193 <!--<category name="test.log4j.JavaLog4J.test" additivity="false">
194 <level value="DEBUG"></level>
195 <appender-ref ref="adDailyLogFile"></appender-ref>
196 </category>-->
197
198 <!-- 控制输出appender项 -->
199 <root>
200 <!-- 控制日志输出的最低级别, 则appender输出日志的最低级别为priority|LevelMin|logger|category中的高级别 -->
201 <priority value="ALL"></priority>
202 <!-- 系统运行日志 {TRACE, ERROR} -->
203 <appender-ref ref="InfoConsole"></appender-ref>
204 <!-- 系统运行的错误日志 {ERROR, FATAL}, 单一 -->
205 <appender-ref ref="SysRunningErrorLog"></appender-ref>
206 <!-- 系统运行的调试日志 {DEBUG}, 大小-->
207 <appender-ref ref="SysRunningDebugLog"></appender-ref>
208 <!-- 系统运行的用户日志 {INFO, WARN}, 每天, LOG -->
209 <appender-ref ref="SysRunCustUseLog"></appender-ref>
210 <!-- 系统运行的用户日志 {INFO, WARN}, 每天, HTM -->
211 <appender-ref ref="SysRunCustUseLogHtm"></appender-ref>
212 <!-- 系统运行的用户日志 {INFO, WARN} 每天, XML -->
213 <appender-ref ref="SysRunCustUseLogXml"></appender-ref>
214 <!-- 系统运行的所有日志 {TRACE, FATAL}, 运行此配置, 需要配置相应的数据库信息 -->
215 <!-- <appender-ref ref="SysRunInfoDB"></appender-ref> -->
216 </root>
217 </log4j:configuration>
Log4J XML 文件配置文件详情,内含日志级别及文件输出等详解
  • properties 配置文件
Java学习-007-Log4J 日志记录配置文件详解及实例源代码Java学习-007-Log4J 日志记录配置文件详解及实例源代码
 1 # adDatabase \u53D1\u9001\u6570\u636E\u5E93\u4FE1\u606F\u914D\u7F6E
2 log4j.rootLogger=INFO,adInfoConsole,adInfoFile,adDailyLogFile,adRollingFile,adInfoHtml,adCust
3 log4j.addivity.org.apache=true
4
5 # Send to console
6 log4j.appender.adInfoConsole=org.apache.log4j.ConsoleAppender
7 # output level
8 log4j.appender.adInfoConsole.Threshold=INFO
9 log4j.appender.adInfoConsole.Target=System.err
10 log4j.appender.adInfoConsole.layout=org.apache.log4j.PatternLayout
11 log4j.appender.adInfoConsole.layout.ConversionPattern={adInfoConsole} - %d - %-5p - [%F] [%t] [%c:%L] - %m%n
12 log4j.appender.adInfoConsole.ImmediateFlush=true
13
14 # Send to file
15 log4j.appender.adInfoFile=org.apache.log4j.FileAppender
16 log4j.appender.adInfoFile.Threshold = INFO
17 log4j.appender.adInfoFile.File=logs/adInfoFile.log
18 log4j.appender.adInfoFile.Append=true
19 log4j.appender.adInfoFile.layout=org.apache.log4j.PatternLayout
20 log4j.appender.adInfoFile.layout.ConversionPattern={adInfoFile} - %d - %-5p - [%F] [%t] [%c:%L] - %m%n
21
22 # Send to daily file
23 log4j.appender.adDailyLogFile = org.apache.log4j.DailyRollingFileAppender
24 log4j.appender.adDailyLogFile.Threshold = ERROR
25 # file path
26 log4j.appender.adDailyLogFile.File = logs/adErrorLogFile.log
27 # default true: add the info to the log file tail; false: rewrite the log file
28 log4j.appender.adDailyLogFile.Append = true
29 # directly output the info
30 log4j.appender.adDailyLogFile.ImmediateFlush = true
31 # format the file name
32 log4j.appender.adDailyLogFile.DatePattern = '-'yyyyMMdd'.log'
33 # '-'yyyy-MM: every month
34 # '-'yyyy-ww: every week
35 # '-'yyyy-MM-dd: every day
36 # '-'yyyy-MM-dd-a: every middle day and night
37 # '-'yyyy-MM-dd-HH: every hour
38 # '-'yyyy-MM-dd-HH-mm: every minute
39 # content format
40 log4j.appender.adDailyLogFile.layout = org.apache.log4j.PatternLayout
41 log4j.appender.adDailyLogFile.layout.ConversionPattern ={adDailyLogFile} - %d - %-5p - [%F] [%t] [%c:%L] - %m%n
42
43 # Send to file
44 log4j.appender.adRollingFile=org.apache.log4j.RollingFileAppender
45 log4j.appender.adRollingFile.Threshold=ERROR
46 log4j.appender.adRollingFile.File=logs/adRollingFile.log
47 log4j.appender.adRollingFile.Append=true
48 # the file size (KB, MB, GB)
49 log4j.appender.adRollingFile.MaxFileSize=1MB
50 # max backup count
51 log4j.appender.adRollingFile.MaxBackupIndex=3
52 log4j.appender.adRollingFile.layout=org.apache.log4j.PatternLayout
53 log4j.appender.adRollingFile.layout.ConversionPattern={adErrorRollingFile} - %d - %-5p - [%F] [%t] [%c:%L] - %m%n
54
55 # Send to html
56 log4j.appender.adInfoHtml = org.apache.log4j.RollingFileAppender
57 log4j.appender.adInfoHtml.Threshold = INFO
58 log4j.appender.adInfoHtml.File = logs/adInfoHtml.html
59 log4j.appender.adInfoHtml.Append = true
60 log4j.appender.adInfoHtml.MaxFileSize = 3MB
61 log4j.appender.adInfoHtml.MaxBackupIndex = 3
62 log4j.appender.adInfoHtml.layout = org.apache.log4j.HTMLLayout
63 # the html file name
64 log4j.appender.adInfoHtml.layout.Title =Logs info for the current running system from Log4J Message
65
66 # Send to database
67 # log4j.appender.adDatabase=org.apache.log4j.jdbc.JDBCAppender
68 # log4j.appender.adDatabase.Threshold=DEBUG
69 # log4j.appender.adDatabase.URL=jdbc:mysql://localhost:3306/test
70 # log4j.appender.adDatabase.driver=com.mysql.jdbc.Driver
71 # log4j.appender.adDatabase.URL=jdbc:microsoft:sqlserver://127.0.0.1:1433;DatabaseName=Aaron
72 # log4j.appender.adDatabase.driver=com.microsoft.jdbc.sqlserver.SQLServerDriver
73 # log4j.appender.adDatabase.URL=jdbc:oracle:thin:@127.0.0.1:1521:aaron
74 # log4j.appender.adDatabase.driver=oracle.jdbc.driver.OracleDriver
75 # log4j.appender.adDatabase.user=hr
76 # log4j.appender.adDatabase.password=hr
77 # log4j.appender.adDatabase.sql=INSERT INTO sysRunInfoLog4J (appenderName, logTime, infoLevel, fileName, threadName, className, lineNumber, infoMsg) VALUES ('adDatabase', '%d', '%p', '%F', '%t', '%c', '%L', '%m')
78 # log4j.appender.adDatabase.layout=org.apache.log4j.PatternLayout
79 # log4j.appender.adDatabase.layout.ConversionPattern=adDatabase %d %p %F %t %c %L %m
80
81 # Custom
82 log4j.appender.adCust=org.apache.log4j.DailyRollingFileAppender
83 log4j.appender.adCust.File=logs/SampleMsgLog4J.xml
84 log4j.appender.adCust.DatePattern='-'yyyyMMdd-HH'.xml'
85 log4j.appender.adCust.layout=org.apache.log4j.xml.XMLLayout
86
87 # Send to mail
88 log4j.appender.adMail=org.apache.log4j.net.SMTPAppender
89 log4j.appender.adMail.Threshold=FATAL
90 log4j.appender.adMail.BufferSize=10
91 log4j.appender.adMail.From=web@www.wuset.com
92 log4j.appender.adMail.SMTPHost=www.wusetu.com
93 log4j.appender.adMail.Subject=Logs info for the current running system from Log4J Message
94 log4j.appender.adMail.To=web@www.wusetu.com
95 log4j.appender.adMail.layout=org.apache.log4j.PatternLayout
96 log4j.appender.adMail.layout.ConversionPattern={adFatalMail} - %d - %-5p - [%F] [%t] [%c:%L] - %m%n
Log4J properties 文件配置详情实例
  • Java Log4J 源代码简单实例
Java学习-007-Log4J 日志记录配置文件详解及实例源代码Java学习-007-Log4J 日志记录配置文件详解及实例源代码
 1 /**
2 * Aaron.ffp Inc.
3 * Copyright (c) 2004-2015 All Rights Reserved.
4 */
5 package main.java.aaron.java.demo;
6
7 import org.apache.log4j.Logger;
8 import org.apache.log4j.PropertyConfigurator;
9 //import org.apache.log4j.xml.DOMConfigurator;
10
11 /**
12 * Log4J 演示实例
13 * @author Aaron.ffp
14 * @version V1.0.0: autoUISelenium main.java.aaron.java.demo Log4JDemo.java, 2015-1-30 13:54:02 Exp $
15 */
16 public class Log4JDemo {
17 private static Logger logger = Logger.getLogger(Log4JDemo.class.getName());
18
19 /**
20 * 方法主入口
21 * @author Aaron.ffp
22 * @version V1.0.0: autoUISelenium main.java.aaron.java.demo Log4JDemo.java main, 2015-1-30 13:54:02 Exp $
23 *
24 * @param args
25 */
26 public static void main(String[] args) {
27 // 初始化log4j的配置文件
28 // DOMConfigurator.configure("src/log4j.xml");
29 PropertyConfigurator.configure("src/log4j.properties");
30
31 // 记录debug级别的信息
32 logger.trace("This is trace message.");
33
34 // 记录debug级别的信息
35 logger.debug("This is debug message.");
36
37 // 记录info级别的信息
38 logger.info("This is info message.");
39
40 // 记录warn级别的信息
41 logger.warn("This is warn message.");
42
43 // 记录error级别的信息
44 logger.error("This is error message.");
45
46 // 记录fatal级别的信息
47 logger.fatal("This is fatal message.");
48 }
49 }
Java Log4J 源代码简单实例

 

至此, Java学习-007-Log4J 日志记录配置文件详解及实例源代码 顺利完结,希望此文能够给初学 Java 的您一份参考。

最后,非常感谢亲的驻足,希望此文能对亲有所帮助。热烈欢迎亲一起探讨,共同进步。非常感谢! ^_^