java项目使用log4j 浅谈在JAVA项目中LOG4J的使用
人气:0一、直接使用:
//输出到项目文件夹下output1.txt文件中 ////////////////////////////// // DEBUG - Here is some DEBUG // INFO - Here is some INFO // WARN - Here is some WARN // ERROR - Here is some ERROR // FATAL - Here is some FATAL ////////////////////////////// package hunnu.sanha.test; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.SimpleLayout; import org.apache.log4j.FileAppender; public class Simpandfile { static Logger logger = Logger.getLogger(Simpandfile.class); public static void main(String args[]) { SimpleLayout layout = new SimpleLayout(); FileAppender appender = null; try { appender = new FileAppender(layout,"output1.txt",false); } catch(Exception e) {} logger.addAppender(appender); logger.setLevel((Level) Level.); logger.debug("Here is some DEBUG"); logger.info("Here is some INFO"); logger.warn("Here is some WARN"); logger.error("Here is some ERROR"); logger.fatal("Here is some FATAL"); } } //按格式输出到项目文件夹下output2.html package hunnu.sanha.test; import java.io.*; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.HTMLLayout; import org.apache.log4j.WriterAppender; public class Htmlandwrite { static Logger logger = Logger.getLogger(Htmlandwrite.class); public static void main(String args[]) { HTMLLayout layout = new HTMLLayout(); WriterAppender appender = null; try { FileOutputStream output = new FileOutputStream("output2.html"); appender = new WriterAppender(layout,output); } catch(Exception e) {} logger.addAppender(appender); logger.setLevel((Level) Level.); logger.debug("Here is some DEBUG"); logger.info("Here is some INFO"); logger.warn("Here is some WARN"); logger.error("Here is some ERROR"); logger.fatal("Here is some FATAL"); } } //输出到控制台 //////////////////////////////////////////////////////////////////////////////////////////////////////////// Milliseconds since program start: 0 Classname of caller: hunnu.sanha.test.Consandpatt Date in ISO8601 format: 2008-07-29 11:02:30,578 Location of log event: hunnu.sanha.test.Consandpatt.main(Consandpatt.java:20) Message: Here is some DEBUG Milliseconds since program start: 15 Classname of caller: hunnu.sanha.test.Consandpatt Date in ISO8601 format: 2008-07-29 11:02:30,593 Location of log event: hunnu.sanha.test.Consandpatt.main(Consandpatt.java:21) Message: Here is some INFO Milliseconds since program start: 15 Classname of caller: hunnu.sanha.test.Consandpatt Date in ISO8601 format: 2008-07-29 11:02:30,593 Location of log event: hunnu.sanha.test.Consandpatt.main(Consandpatt.java:22) Message: Here is some WARN Milliseconds since program start: 15 Classname of caller: hunnu.sanha.test.Consandpatt Date in ISO8601 format: 2008-07-29 11:02:30,593 Location of log event: hunnu.sanha.test.Consandpatt.main(Consandpatt.java:23) Message: Here is some ERROR Milliseconds since program start: 15 Classname of caller: hunnu.sanha.test.Consandpatt Date in ISO8601 format: 2008-07-29 11:02:30,593 Location of log event: hunnu.sanha.test.Consandpatt.main(Consandpatt.java:24) Message: Here is some FATAL /////////////////////////////////////////////////////// package hunnu.sanha.test; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.PatternLayout; import org.apache.log4j.ConsoleAppender; public class Consandpatt { static Logger logger = Logger.getLogger(Consandpatt.class); public static void main(String args[]) { // Note, %n is newline String pattern = "Milliseconds since program start: %r %n"; pattern += "Classname of caller: %C %n"; pattern += "Date in ISO8601 format: %d{ISO8601} %n"; pattern += "Location of log event: %l %n"; pattern += "Message: %m %n %n"; PatternLayout layout = new PatternLayout(pattern); ConsoleAppender appender = new ConsoleAppender(layout); logger.addAppender(appender); logger.setLevel((Level) Level.); logger.debug("Here is some DEBUG"); logger.info("Here is some INFO"); logger.warn("Here is some WARN"); logger.error("Here is some ERROR"); logger.fatal("Here is some FATAL"); } }
二、使用配置文件(都直接放到项目文件夹下)
//xmllog4jconfig.xml <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"> <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"> <appender name="appender" class="org.apache.log4j.FileAppender"> <param name="File" value="Indentify-Log.txt"/> <param name="Append" value="false"/> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%d [%t] %p - %m%n"/> </layout> </appender> <root> <priority value ="debug"/> <appender-ref ref="appender"/> </root> </log4j:configuration> //Externalxmltest.java package hunnu.sanha.external; import org.apache.log4j.Logger; import org.apache.log4j.xml.DOMConfigurator; public class Externalxmltest { static Logger logger = Logger.getLogger(Externalxmltest.class); public static void main(String args[]) { DOMConfigurator.configure("xmllog4jconfig.xml"); logger.debug("Here is some DEBUG"); logger.info("Here is some INFO"); logger.warn("Here is some WARN"); logger.error("Here is some ERROR"); logger.fatal("Here is some FATAL"); } } //结果输出到Indentify-Log.txt文件中 2008-07-29 10:48:11,375 [main] DEBUG - Here is some DEBUG 2008-07-29 10:48:11,375 [main] INFO - Here is some INFO 2008-07-29 10:48:11,375 [main] WARN - Here is some WARN 2008-07-29 10:48:11,375 [main] ERROR - Here is some ERROR 2008-07-29 10:48:11,375 [main] FATAL - Here is some FATAL // plainlog4jconfig.txt # initialise root logger with level DEBUG and call it BLAH log4j.rootLogger=DEBUG, BLAH # add a ConsoleAppender to the logger BLAH log4j.appender.BLAH=org.apache.log4j.ConsoleAppender # set set that layout to be SimpleLayout log4j.appender.BLAH.layout=org.apache.log4j.SimpleLayout //Externalplaintest.java package hunnu.sanha.external; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; public class Externalplaintest { static Logger logger = Logger.getLogger(Externalplaintest.class); public static void main(String args[]) { PropertyConfigurator.configure("plainlog4jconfig.txt"); logger.debug("Here is some DEBUG"); logger.info("Here is some INFO"); logger.warn("Here is some WARN"); logger.error("Here is some ERROR"); logger.fatal("Here is some FATAL"); } } //结果输出到控制台 DEBUG - Here is some DEBUG INFO - Here is some INFO WARN - Here is some WARN ERROR - Here is some ERROR FATAL - Here is some FATAL
附加:
2.1. 日志信息的优先级
分为OFF、FATAL、ERROR、WARN、INFO、DEBUG、ALL或者您定义的级别。
Log4j建议只使用四个级别,优先级从高到低分别是ERROR、WARN、INFO、DEBUG。通过在这里定义的级别,您可以控制到应用程序中相应级别的日志信息的开关。
假如在一个级别为q的Logger中发生一个级别为p的日志请求,如果p>=q,那么请求将被启用。这是Log4j的核心原则。
比如在这里定义了INFO级别,则应用程序中所有DEBUG级别的日志信息将不被打印出来;
2.2. 输出源的使用
有选择的能用或者禁用日志请求仅仅是Log4j的一部分功能。Log4j允许日志请求被输出到多个输出源。用Log4j的话说,一个输出源被称做一个Appender。
Appender包括console(控制台), files(文件), GUI components(图形的组件), remote socket servers(socket 服务), JMS(java信息服务), NT Event Loggers(NT的事件日志), and remote UNIX Syslog daemons(远程UNIX的后台日志服务)。它也可以做到异步记录。
一个logger可以设置超过一个的appender。
用addAppender 方法添加一个appender到一个给定的logger。对于一个给定的logger它每个生效的日志请求都被转发到该logger所有的appender上和该logger的父辈logger的appender上。
2.2.1. ConsoleAppender
如果使用ConsoleAppender,那么log信息将写到Console。效果等同于直接把信息打印到System.out上了。
2.2.2. FileAppender
使用FileAppender,那么log信息将写到指定的文件中。这应该是比较经常使用到的情况。
相应地,在配置文件中应该指定log输出的文件名。如下配置指定了log文件名为dglog.txt
log4j.appender.A2.File=dglog.txt
注意将A2替换为具体配置中Appender的别名。
2.2.3. DailyRollingAppender
使用FileAppender可以将log信息输出到文件中,但是如果文件太大了读起来就不方便了。这时就可以使用DailyRollingAppender。DailyRollingAppender可以把Log信息输出到按照日期来区分的文件中。配置文件就会每天产生一个log文件,每个log文件只记录当天的log信息:
log4j.appender.A2=org.apache.log4j.DailyRollingFileAppender
log4j.appender.A2.file=dglog
log4j.appender.A2.DatePattern='.'yyyy-MM-dd
log4j.appender.A2.layout=org.apache.log4j.PatternLayout
log4j.appender.A2.layout.ConversionPattern= %5r %-5p %c{2} - %m%n
2.2.4. org.apache.log4j.RollingFileAppender
文件大小到达指定尺寸的时候产生一个新的文件。
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File= ../logs/dglog.log
# Control the maximum log file size
log4j.appender.R.MaxFileSize=100KB
# Archive log files (one backup file here)
log4j.appender.R.MaxBackupIndex=1
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n
这个配置文件指定了输出源R,是一个轮转日志文件。最大的文件是100KB,当一个日志文件达到最大尺寸时,Log4J会自动把example.log重命名为dglog.log.1,然后重建一个新的dglog.log文件,依次轮转。
2.2.5. org.apache.log4j.WriterAppender
将日志信息以流格式发送到任意指定的地方。
2.3. Layout的配置
Layout指定了log信息输出的样式。
2.3.1. 布局样式
org.apache.log4j.HTMLLayout(以HTML表格形式布局),
org.apache.log4j.PatternLayout(可以灵活地指定布局模式),
org.apache.log4j.SimpleLayout(包含日志信息的级别和信息字符串),
org.apache.log4j.TTCCLayout(包含日志产生的时间、线程、类别等等信息)
2.3.2. 格式
%m 输出代码中指定的消息
%p 输出优先级,即DEBUG,INFO,WARN,ERROR,FATAL
%r 输出自应用启动到输出该log信息耗费的毫秒数
%c 输出所属的类目,通常就是所在类的全名
%t 输出产生该日志事件的线程名
%n 输出一个回车换行符,Windows平台为"rn",Unix平台为"n"
%d 输出日志时间点的日期或时间,默认格式为ISO8601,也可以在其后指定格式,比如:%d{yyy MMM dd HH:mm:ss,SSS},输出类似:2002年10月18日 22:10:28,921
%l 输出日志事件的发生位置,包括类目名、发生的线程,以及在代码中的行数。举例:Testlog4.main(Test Log4.java:10)
2.3.3. 例子
例子1:显示日期和log信息
log4j.appender.A2.layout=org.apache.log4j.PatternLayout
log4j.appender.A2.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %m%n
打印的信息是:
2002-11-12 11:49:42,866 SELECT * FROM Role WHERE 1=1 order by createDate desc
例子2:显示日期,log发生地方和log信息
log4j.appender.A2.layout=org.apache.log4j.PatternLayout
log4j.appender.A2.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %l "#" %m%n
2002-11-12 11:51:46,313 cn.net.unet.weboa.system.dao.RoleDAO.select(RoleDAO.java:409) "#"
SELECT * FROM Role WHERE 1=1 order by createDate desc
例子3:显示log级别,时间,调用方法,log信息
log4j.appender.A2.layout=org.apache.log4j.PatternLayout
log4j.appender.A2.layout.ConversionPattern=[%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS}
method:%l%n%m%n
log信息:
[DEBUG] 2002-11-12 12:00:57,376
method:cn.net.unet.weboa.system.dao.RoleDAO.select(RoleDAO.java:409)
SELECT * FROM Role WHERE 1=1 order by createDate desc
2.4. 配置文件的例子:
log4j.rootLogger=DEBUG
#将DAO层log记录到DAOLog,allLog中
log4j.logger.DAO=DEBUG,A2,A4
#将逻辑层log记录到BusinessLog,allLog中
log4j.logger.Businesslog=DEBUG,A3,A4
#A1--打印到屏幕上
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-5p [%t] %37c %3x - %m%n
#A2--打印到文件DAOLog中--专门为DAO层服务
log4j.appender.A2=org.apache.log4j.DailyRollingFileAppender
log4j.appender.A2.file=DAOLog
log4j.appender.A2.DatePattern='.'yyyy-MM-dd
log4j.appender.A2.layout=org.apache.log4j.PatternLayout
log4j.appender.A2.layout.ConversionPattern=[%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS}
method:%l%n%m%n
#A3--打印到文件BusinessLog中--专门记录逻辑处理层服务log信息
log4j.appender.A3=org.apache.log4j.DailyRollingFileAppender
log4j.appender.A3.file=BusinessLog
log4j.appender.A3.DatePattern='.'yyyy-MM-dd
log4j.appender.A3.layout=org.apache.log4j.PatternLayout
log4j.appender.A3.layout.ConversionPattern=[%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS}
method:%l%n%m%n
#A4--打印到文件alllog中--记录所有log信息
log4j.appender.A4=org.apache.log4j.DailyRollingFileAppender
log4j.appender.A4.file=alllog
log4j.appender.A4.DatePattern='.'yyyy-MM-dd
log4j.appender.A4.layout=org.apache.log4j.PatternLayout
log4j.appender.A4.layout.ConversionPattern=[%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS}
method:%l%n%m%n
以上这篇浅谈在JAVA项目中LOG4J的使用就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。
加载全部内容