vlambda博客
学习文章列表

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

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

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

  • xml 配置文件

<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"><!-- ========================== 日志输出等级 ================================ --><!-- OFF:最高等级, 用于关闭所有日志记录 --><!-- FATAL:输出严重级别的消息 --><!-- ERROR:输出错误级别的消息 --><!-- WARN:输出警告级别的消息 --><!-- INFO:输出信息级别的消息 --><!-- DEBUG:输出调试级别的消息 --><!-- TRACE:输出跟踪级别的消息 --><!-- ALL:最低等级, 用于打开所有日志记录 --><!-- 只有当输出日期的级别大于或等于为日志配置器配置的日志级别时, 这个方法才会执行. 指定日志器的日志级别, 不同的日志器会实现不同的日志输出方案 -->
<!-- ========================== 自定义输出格式说明 ================================ --><!-- %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) --><!-- ========================================================================== -->
<!-- ========================== 输出方式说明================================ --><!-- Log4j提供的appender有以下几种: --><!-- org.apache.log4j.ConsoleAppender(控制台), --><!-- org.apache.log4j.FileAppender(文件), --><!-- org.apache.log4j.DailyRollingFileAppender(每天产生一个日志文件), --><!-- org.apache.log4j.RollingFileAppender(文件大小到达指定尺寸的时候产生一个新的文件), --><!-- org.apache.log4j.WriterAppender(将日志信息以流格式发送到任意指定的地方) --><!-- ========================================================================== -->
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"> <!-- 系统运行日志 {TRACE, ERROR} --> <appender name="InfoConsole" class="org.apache.log4j.ConsoleAppender"> <!-- 不进行缓存, 直接输出 --> <param name="ImmediateFlush" value="true"></param> <!-- 指定输出控制台, 默认情况下是 System.out --> <param name="Target" value="System.err"></param> <!-- 设置输出文件项目和格式 --> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="{InfoConsole} - %d - %-5p - [%F] [%t] [%c:%L] - %m%n" /> </layout>
<!--限制输出级别 --> <filter class="org.apache.log4j.varia.LevelRangeFilter"> <param name="LevelMax" value="ERROR" ></param> <param name="LevelMin" value="TRACE" ></param> </filter> </appender>
<!-- 系统运行的错误日志 {ERROR, FATAL}, 单一 --> <appender name="SysRunningErrorLog" class="org.apache.log4j.FileAppender"> <!-- 设置File参数:日志输出文件名 --> <param name="File" value="logs/SysRunningErrorLog.log" ></param> <!-- 设置在重新启动服务时,在原有日志的基础添加新日志 --> <param name="Append" value="true" ></param> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="{SysRunningErrorLog} - %d - %-5p - [%F] [%t] [%c:%L] - %m%n" ></param> </layout> <filter class="org.apache.log4j.varia.LevelRangeFilter"> <param name="LevelMax" value="FATAL" ></param> <param name="LevelMin" value="ERROR" ></param> </filter> </appender> <!-- 系统运行的调试日志 {DEBUG}, 大小--> <appender name="SysRunningDebugLog" class="org.apache.log4j.RollingFileAppender"> <param name="File" value="logs/SysRunningDebugLog.log" ></param> <param name="Append" value="true" ></param> <!-- 设置文件大小 --> <param name="MaxFileSize" value="5MB" ></param> <!-- 设置文件备份 --> <param name="MaxBackupIndex" value="21" ></param> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="{SysRunningDebugLog} - %d - %-5p - [%F] [%t] [%c:%L] - %m%n" ></param> </layout> <filter class="org.apache.log4j.varia.LevelRangeFilter"> <param name="LevelMax" value="DEBUG" ></param> <param name="LevelMin" value="DEBUG" ></param> </filter> </appender> <!-- 系统运行的用户日志 {INFO, WARN}, 每天, LOG --> <appender name="SysRunCustUseLog" class="org.apache.log4j.DailyRollingFileAppender"> <param name="File" value="logs/SysRunCustUseLog.log" ></param> <param name="Append" value="true" ></param> <param name="ImmediateFlush" value="true" ></param> <param name="DatePattern" value="'-'yyyyMMdd'.log'" ></param> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="{SysRunCustUseLog} - %d - %-5p - [%F] [%t] [%c:%L] - %m%n" ></param> </layout> <filter class="org.apache.log4j.varia.LevelRangeFilter"> <param name="LevelMax" value="WARN" ></param> <param name="LevelMin" value="INFO" ></param> </filter> </appender> <!-- 系统运行的用户日志 {INFO, WARN}, 每天, HTM --> <appender name="SysRunCustUseLogHtm" class="org.apache.log4j.DailyRollingFileAppender"> <param name="File" value="logs/SysRunCustUseLogHtm.html" ></param> <param name="Append" value="true" ></param> <param name="ImmediateFlush" value="true" ></param> <param name="DatePattern" value="'-'yyyyMMdd'.html'" ></param> <layout class="org.apache.log4j.HTMLLayout"> <param name="Title" value="Logs info for the current running system from Log4J Message"></param> </layout> <filter class="org.apache.log4j.varia.LevelRangeFilter"> <param name="LevelMax" value="WARN" ></param> <param name="LevelMin" value="INFO" ></param> </filter> </appender> <!-- 系统运行的用户日志 {INFO, WARN} 每天, XML --> <appender name="SysRunCustUseLogXml" class="org.apache.log4j.DailyRollingFileAppender"> <param name="File" value="logs/SysRunCustUseLogXml.xml"></param> <param name="DatePattern" value="'-'yyyyMMdd'.xml'"></param> <layout class="org.apache.log4j.xml.XMLLayout"></layout> <filter class="org.apache.log4j.varia.LevelRangeFilter"> <param name="LevelMax" value="WARN"></param> <param name="LevelMin" value="INFO"></param> </filter> </appender> <!-- 系统运行的所有日志 {TRACE, FATAL} --> <!-- MySQL, sqlserver JDBC 连接实例 <param name="URL" value="jdbc:mysql://127.0.0.1:3306/test" ></param> <param name="driver" value="com.mysql.jdbc.Driver" ></param> <param name="URL" value="jdbc:microsoft:sqlserver://127.0.0.1:1433;DatabaseName=Aaron" ></param> <param name="driver" value="com.microsoft.jdbc.sqlserver.SQLServerDriver" ></param> --> <!-- <appender name="SysRunInfoDB" class="org.apache.log4j.jdbc.JDBCAppender"> <param name="URL" value="jdbc:oracle:thin:@127.0.0.1:1521:aaron" ></param> <param name="driver" value="oracle.jdbc.driver.OracleDriver" ></param> <param name="user" value="hr" ></param> <param name="password" value="hr" ></param> <layout class="org.apache.log4j.PatternLayout"> <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> </layout> <filter class="org.apache.log4j.varia.LevelRangeFilter"> <param name="LevelMax" value="FATAL"></param> <param name="LevelMin" value="TRACE"></param> </filter> </appender> --> <!-- 发邮件(只有ERROR时才会发送!) --> <!-- <appender name="adMail" class="org.apache.log4j.net.SMTPAppender"> <param name="threshold" value="debug"></param> <param name="BufferSize" value="512"></param> <param name="From" value="[email protected]"></param> <param name="SMTPHost" value="smtp.163.com"></param> <param name="Subject" value="Logs info for the current running system from Log4J Message"></param> <param name="To" value="[email protected]"></param> <param name="SMTPUsername" value="test"></param> <param name="SMTPPassword" value="test"></param> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="{adMail} - %d - %-5p - [%F] [%t] [%c:%L] - %m%n"></param> </layout> <filter class="org.apache.log4j.varia.LevelRangeFilter"> <param name="LevelMax" value="FATAL"></param> <param name="LevelMin" value="ERROR"></param> </filter> </appender> -->
<!--- 异步测试,当日志达到缓存区大小时候执行所包的appender --> <appender name="ASYNC" class="org.apache.log4j.AsyncAppender"> <param name="BufferSize" value="256"></param> <appender-ref ref="SysRunningDebugLog"></appender-ref> <appender-ref ref="SysRunCustUseLog"></appender-ref> <appender-ref ref="SysRunCustUseLogHtm"></appender-ref> <appender-ref ref="SysRunCustUseLogXml"></appender-ref> </appender>
<!--通过<logger>的定义可以将各个包中的类日志输出到不同的日志文件中 --> <!--<logger name="test.log4j" additivity="false"> <level value="INFO"></level> <appender-ref ref="InfoConsole"></appender-ref> <appender-ref ref="adDatabase"></appender-ref> <appender-ref ref="SysRunningErrorLog"></appender-ref> </logger>--> <!--通过<category></category>的定义可以将各个包中的类日志输出到不同的日志文件中 --> <!--<category name="test.log4j.JavaLog4J.test" additivity="false"> <level value="DEBUG"></level> <appender-ref ref="adDailyLogFile"></appender-ref> </category>-->
<!-- 控制输出appender项 --> <root> <!-- 控制日志输出的最低级别, 则appender输出日志的最低级别为priority|LevelMin|logger|category中的高级别 --> <priority value="ALL"></priority> <!-- 系统运行日志 {TRACE, ERROR} --> <appender-ref ref="InfoConsole"></appender-ref> <!-- 系统运行的错误日志 {ERROR, FATAL}, 单一 --> <appender-ref ref="SysRunningErrorLog"></appender-ref> <!-- 系统运行的调试日志 {DEBUG}, 大小--> <appender-ref ref="SysRunningDebugLog"></appender-ref> <!-- 系统运行的用户日志 {INFO, WARN}, 每天, LOG --> <appender-ref ref="SysRunCustUseLog"></appender-ref> <!-- 系统运行的用户日志 {INFO, WARN}, 每天, HTM --> <appender-ref ref="SysRunCustUseLogHtm"></appender-ref> <!-- 系统运行的用户日志 {INFO, WARN} 每天, XML --> <appender-ref ref="SysRunCustUseLogXml"></appender-ref> <!-- 系统运行的所有日志 {TRACE, FATAL}, 运行此配置, 需要配置相应的数据库信息 --> <!-- <appender-ref ref="SysRunInfoDB"></appender-ref> --> </root></log4j:configuration>  

properties 配置文件

# adDatabase \u53D1\u9001\u6570\u636E\u5E93\u4FE1\u606F\u914D\u7F6Elog4j.rootLogger=INFO,adInfoConsole,adInfoFile,adDailyLogFile,adRollingFile,adInfoHtml,adCustlog4j.addivity.org.apache=true
# Send to consolelog4j.appender.adInfoConsole=org.apache.log4j.ConsoleAppender# output levellog4j.appender.adInfoConsole.Threshold=INFOlog4j.appender.adInfoConsole.Target=System.errlog4j.appender.adInfoConsole.layout=org.apache.log4j.PatternLayoutlog4j.appender.adInfoConsole.layout.ConversionPattern={adInfoConsole} - %d - %-5p - [%F] [%t] [%c:%L] - %m%nlog4j.appender.adInfoConsole.ImmediateFlush=true
# Send to filelog4j.appender.adInfoFile=org.apache.log4j.FileAppenderlog4j.appender.adInfoFile.Threshold = INFOlog4j.appender.adInfoFile.File=logs/adInfoFile.loglog4j.appender.adInfoFile.Append=truelog4j.appender.adInfoFile.layout=org.apache.log4j.PatternLayoutlog4j.appender.adInfoFile.layout.ConversionPattern={adInfoFile} - %d - %-5p - [%F] [%t] [%c:%L] - %m%n
# Send to daily filelog4j.appender.adDailyLogFile = org.apache.log4j.DailyRollingFileAppenderlog4j.appender.adDailyLogFile.Threshold = ERROR# file pathlog4j.appender.adDailyLogFile.File = logs/adErrorLogFile.log# default true: add the info to the log file tail; false: rewrite the log filelog4j.appender.adDailyLogFile.Append = true# directly output the infolog4j.appender.adDailyLogFile.ImmediateFlush = true# format the file namelog4j.appender.adDailyLogFile.DatePattern = '-'yyyyMMdd'.log'# '-'yyyy-MM: every month# '-'yyyy-ww: every week# '-'yyyy-MM-dd: every day# '-'yyyy-MM-dd-a: every middle day and night# '-'yyyy-MM-dd-HH: every hour# '-'yyyy-MM-dd-HH-mm: every minute# content formatlog4j.appender.adDailyLogFile.layout = org.apache.log4j.PatternLayoutlog4j.appender.adDailyLogFile.layout.ConversionPattern ={adDailyLogFile} - %d - %-5p - [%F] [%t] [%c:%L] - %m%n
# Send to filelog4j.appender.adRollingFile=org.apache.log4j.RollingFileAppenderlog4j.appender.adRollingFile.Threshold=ERRORlog4j.appender.adRollingFile.File=logs/adRollingFile.loglog4j.appender.adRollingFile.Append=true# the file size (KB, MB, GB)log4j.appender.adRollingFile.MaxFileSize=1MB# max backup countlog4j.appender.adRollingFile.MaxBackupIndex=3log4j.appender.adRollingFile.layout=org.apache.log4j.PatternLayoutlog4j.appender.adRollingFile.layout.ConversionPattern={adErrorRollingFile} - %d - %-5p - [%F] [%t] [%c:%L] - %m%n
# Send to htmllog4j.appender.adInfoHtml = org.apache.log4j.RollingFileAppender log4j.appender.adInfoHtml.Threshold = INFOlog4j.appender.adInfoHtml.File = logs/adInfoHtml.htmllog4j.appender.adInfoHtml.Append = true log4j.appender.adInfoHtml.MaxFileSize = 3MBlog4j.appender.adInfoHtml.MaxBackupIndex = 3log4j.appender.adInfoHtml.layout = org.apache.log4j.HTMLLayout# the html file namelog4j.appender.adInfoHtml.layout.Title =Logs info for the current running system from Log4J Message
# Send to database# log4j.appender.adDatabase=org.apache.log4j.jdbc.JDBCAppender# log4j.appender.adDatabase.Threshold=DEBUG# log4j.appender.adDatabase.URL=jdbc:mysql://localhost:3306/test# log4j.appender.adDatabase.driver=com.mysql.jdbc.Driver# log4j.appender.adDatabase.URL=jdbc:microsoft:sqlserver://127.0.0.1:1433;DatabaseName=Aaron# log4j.appender.adDatabase.driver=com.microsoft.jdbc.sqlserver.SQLServerDriver# log4j.appender.adDatabase.URL=jdbc:oracle:thin:@127.0.0.1:1521:aaron# log4j.appender.adDatabase.driver=oracle.jdbc.driver.OracleDriver# log4j.appender.adDatabase.user=hr# log4j.appender.adDatabase.password=hr# log4j.appender.adDatabase.sql=INSERT INTO sysRunInfoLog4J (appenderName, logTime, infoLevel, fileName, threadName, className, lineNumber, infoMsg) VALUES ('adDatabase', '%d', '%p', '%F', '%t', '%c', '%L', '%m')# log4j.appender.adDatabase.layout=org.apache.log4j.PatternLayout# log4j.appender.adDatabase.layout.ConversionPattern=adDatabase %d %p %F %t %c %L %m
# Customlog4j.appender.adCust=org.apache.log4j.DailyRollingFileAppenderlog4j.appender.adCust.File=logs/SampleMsgLog4J.xmllog4j.appender.adCust.DatePattern='-'yyyyMMdd-HH'.xml'log4j.appender.adCust.layout=org.apache.log4j.xml.XMLLayout
# Send to maillog4j.appender.adMail=org.apache.log4j.net.SMTPAppenderlog4j.appender.adMail.Threshold=FATALlog4j.appender.adMail.BufferSize=10[email protected]log4j.appender.adMail.SMTPHost=www.wusetu.comlog4j.appender.adMail.Subject=Logs info for the current running system from Log4J Message[email protected]log4j.appender.adMail.layout=org.apache.log4j.PatternLayoutlog4j.appender.adMail.layout.ConversionPattern={adFatalMail} - %d - %-5p - [%F] [%t] [%c:%L] - %m%n

Java Log4J 源代码简单实例

/** * Aaron.ffp Inc. * Copyright (c) 2004-2015 All Rights Reserved. */package main.java.aaron.java.demo;
import org.apache.log4j.Logger;import org.apache.log4j.PropertyConfigurator;//import org.apache.log4j.xml.DOMConfigurator;
/** * Log4J 演示实例 * @author Aaron.ffp * @version V1.0.0: autoUISelenium main.java.aaron.java.demo Log4JDemo.java, 2015-1-30 13:54:02 Exp $ */public class Log4JDemo { private static Logger logger = Logger.getLogger(Log4JDemo.class.getName());
/** * 方法主入口 * @author Aaron.ffp * @version V1.0.0: autoUISelenium main.java.aaron.java.demo Log4JDemo.java main, 2015-1-30 13:54:02 Exp $ * * @param args */ public static void main(String[] args) { // 初始化log4j的配置文件// DOMConfigurator.configure("src/log4j.xml"); PropertyConfigurator.configure("src/log4j.properties"); // 记录debug级别的信息 logger.trace("This is trace message."); // 记录debug级别的信息 logger.debug("This is debug message.");
// 记录info级别的信息 logger.info("This is info message."); // 记录warn级别的信息 logger.warn("This is warn message.");
// 记录error级别的信息 logger.error("This is error message."); // 记录fatal级别的信息 logger.fatal("This is fatal message."); }}

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

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