转载自:http://wiki.apache.org/logging-log4j/Log4jXmlFormat
Log4j XML Configuration Primer
Basic example
Below is a basic xml configuration file for log4j that will get you started:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"> <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"> <appender name="console" class="org.apache.log4j.ConsoleAppender"> <param name="Target" value="System.out"/> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%-5p %c{1} - %m%n"/> </layout> </appender> <root> <priority value ="debug" /> <appender-ref ref="console" /> </root> </log4j:configuration>
This will print all debug or higher messages to the console/screen. Items of note:
-
The appender is defined first, with a name (in this case "console"). A layout is defined for the appender (in this case PatternLayout ), and a pattern is defined for the layout. What is required for the layout is layout specific, so check the javadoc description for the layout class you choose to use ( PatternLayout is used most commonly).
- No loggers are defined in this example, but the configuration for the "root" logger is defined. It is configured to level debug, and the appender named "console" is attached to it. All loggers inherit from root, so in this example, all debug or higher messages from all loggers will be printed to the console appender.
XML Configuration Format
In order to better understand the more detailed examples, it is useful to understand the expected format for the xml configuration files. This is defined by the log4j.dtd which is located in the log4j distribution jar in the package org.apache.log4j.xml. The contents of this file will not be listed in its entirety, so please feel free to open/print the file yourself. If you are not familiar with xml dtd file formats, then you should go find a good book on that subject first.
Near the beginning of the file is the following declaration:
<!ELEMENT log4j:configuration (renderer*, appender*,(category|logger)*,root?, categoryFactory?)>
This element defines the expected structure of the xml configuration file: 0 or more renderer elements, followed by jocuri barbie0 or more appender elements, followed by 0 or more logger elements, followed by 0 or 1 root element, followed by 0 or 1 categoryFactory element. If this order is not followed, then errors will be printed by the xml parser at the time the xml file is read in. Also, as a note, the "category" element is the same as the logger element. Prior to log4j version 1.2, loggers were known as category. Much of the documentation still refers to category. Just understand that they are the same thing.
Further along in the log4j.dtd is the following declaration which defines the allowed attributes:
<!ATTLIST log4j:configuration xmlns:log4j CDATA #FIXED "http://jakarta.apache.org/log4j/" threshold (all|debug|info|warn|error|fatal|off|null) "null" debug (true|false|null) "null" >
-
debug - Probably the most important attribute for log4:configuration, setting it to "true" will print out information as the configuration file is read and used to configure the log4j environment. Very useful when trying to fiure out why your configuration file is not doing what you expect.
-
threshold - <yet to be described>
Understanding the expected structure of the xml configuration file makes it easier to concentrate on the specific elements one needs to configure.
Appender Configuration
One can instrument all the code one writes to output useful debug trace messages, but if log4j is not configured to have at least one appender, all will be for naught. None of the useful messages will be displayed anywhere.
Looking again to the log4j.dtd, appender elements are declared to be:
<!ELEMENT appender (errorHandler?, param*, layout?, filter*, appender-ref*)> <!ATTLIST appender name ID #REQUIRED class CDATA #REQUIRED >
An appender element must have name and class attributes. The name is the value used to reference the appender in the rest of the configuration file. The class attribute should be the fully qualified class name of the appender class to use (ie org.apache.log4j.ConsoleAppender ).
An appender element can also contain child elements:
-
0 or 1 errorHandler element - <yet to be described>
-
0 or more param elements - Each appender can be configured with setting specific to the functioning of the appender. This is implemented by getter and setter methods in the appender class. The param element is used to access the setter methods. The format for param elements is simple; they are atomic elements with a name attribute and a value attribute. The name attribute should be the name of the setter method with the "set" part of the method name omitted (ie method name "setTarget" would be "Target"). The value attribute is the value the setter method should be set with.
-
0 or 1 layout element - Not all appenders use or require a layout. For appenders that do, the layout element defines what layout class to use. The layout element has one attribute, class, which is the fully qualified class name of the layout class to use. Similar to the appender element, the layout element is allowed to have 0 or more param child elements. Again, the param elements are used to set specific values for the layout class, which varies based on what layout class is used.
-
0 or more filter elements - See the Filter Configuration section below for more details.
-
0 or more appender-ref elements - <yet to be described>
So, from the above, the simple example of the appender named "console" from the basic example starts to make more sense:
<appender name="console" class="org.apache.log4j.ConsoleAppender"> <param name="Target" value="System.out"/> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%-5p %c{1} - %m%n"/> </layout> </appender>
The name of of the appender is "console" and this is the name that is used to refer to the appender in the rest of the configuration file. The class to use for the appender is org.apache.log4j.ConsoleAppender .
The console appender has one param element defined. Looking at the javadoc for ConsoleAppender , the setTarget method is used to choose which console stream to print messages to, System.out or System.err. The example configures the appender to use System.out.
The console appender also has a layout element defined which uses org.apache.log4j.PatternLayout . Looking at the javadoc for PatternLayout , the setConversionPattern method takes a string describing the layout for messages. The details of this format can also be found in the javadoc.
The details of the configuration for a specific appender class vary from class to class. Your best bet is to review the javadoc for the appender class you want to use. Pay particular attention to the setter property methods and the values they expect. Each setter method can be accessed using the param element in the xml configuration.
Currently, the following appender classes exist:
-
org.apache.log4j.ConsoleAppender ConsoleAppender
-
org.apache.log4j.FileAppender FileAppender
-
org.apache.log4j.jdbc.JDBCAppender JDBCAppender
-
org.apache.log4j.AsyncAppender AsyncAppender
-
org.apache.log4j.net.JMSAppender JMSAppender
-
org.apache.log4j.lf5.LF5Appender LF5Appender
-
org.apache.log4j.nt.NTEventLogAppender NTEventLogAppender
-
org.apache.log4j.varia.NullAppender NullAppender
-
org.apache.log4j.net.SMTPAppender SMTPAppender
-
org.apache.log4j.net.SocketAppender SocketAppender
-
org.apache.log4j.net.SocketHubAppender SocketHubAppender
-
org.apache.log4j.net.SyslogAppender SyslogAppender
-
org.apache.log4j.net.TelnetAppender TelnetAppender
-
org.apache.log4j.WriterAppender WriterAppender
Logger Configuration
Now the appenders are configured. But how to configure loggers to output messages at a certain level? How to configure loggers to output to specific appender? Welcome to logger configuration.
The most important logger you need to configure is the root logger. From the simple example, this was done with the following configuration:
<root> <priority value ="debug" /> <appender-ref ref="console" /> </root>
The root logger is configured to output log message at level "debug" or higher to the appender named "console". All loggers inherit their settings from the root logger, so with no other configuration settings, all loggers will output all of their messages to the "console" appender automatically. This may be fine for simple debugging, but eventually more specific logger configuration is going to be required.
Looking again to the log4j.dtd, logger elements are declared to be:
<!ELEMENT logger (level?,appender-ref*)> <!ATTLIST logger name ID #REQUIRED additivity (true|false) "true" >
A logger element must have a name attribute. This is the name of the logger used when creating the Logger instance(usually the fully qualified class name). It can also have an optional additivity attribute. More on this later.
A logger element can also contain child elements:
-
0 or 1 level element - This defines the level of log messages that will be allowed to be logged for this logger. Normal usage has a value of "debug", "info", "warn", "error", or "fatal". Only that level or above will be reported to the log.
-
0 or more appender-ref elements - This references a defined appender that log messages from this logger should be directed to. Appender-ref elements are simple elements that have a ref attribute. The value for this attribute should be the name of the appender.
A typical logger configuration element would look similar to this:
<logger name="com.mycompany.apackage.MyClass"> <level value="info"/> </logger>
Logger Inheritance
<yet to be described>
Additivity
The output of a log statement of logger C will go to all the appenders in C and its ancestors. This is the meaning of the term "appender additivity".
However, if an ancestor of logger C, say P, has the additivity flag set to false, then C's output will be directed to all the appenders in C and it's ancestors upto and including P but not the appenders in any of the ancestors of P.
Loggers have their additivity flag set to true by default.
Example config;
<logger name="com.eatmutton.muttonsite.torque" additivity="false"> <level value="info" /> <appender-ref ref="local-torque" /> </logger>
Additivitiy section taken from http://logging.apache.org/log4j/docs/manual.html.
Converting Configuration Files To XML format
I have converted the configuration examples from the log4j manual to xml format. Hopefully people can use this to convert their own configuration files.
Example 1
# Set root logger level to DEBUG and its only appender to A1. log4j.rootLogger=DEBUG, A1 # A1 is set to be a ConsoleAppender. log4j.appender.A1=org.apache.log4j.ConsoleAppender # A1 uses PatternLayout. log4j.appender.A1.layout=org.apache.log4j.PatternLayout log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"> <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"> <!-- A1 is set to be a ConsoleAppender --> <appender name="A1" class="org.apache.log4j.ConsoleAppender"> <!-- A1 uses PatternLayout --> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%-4r [%t] %-5p %c %x - %m%n"/> </layout> </appender> <root> <!-- Set root logger level to DEBUG and its only appender to A1 --> <priority value ="debug" /> <appender-ref ref="A1" /> </root> </log4j:configuration>
Example 2
log4j.rootLogger=DEBUG, A1 log4j.appender.A1=org.apache.log4j.ConsoleAppender log4j.appender.A1.layout=org.apache.log4j.PatternLayout # Print the date in ISO 8601 format log4j.appender.A1.layout.ConversionPattern=%d [%t] %-5p %c - %m%n # Print only messages of level WARN or above in the package com.foo. log4j.logger.com.foo=WARN
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"> <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"> <appender name="A1" class="org.apache.log4j.ConsoleAppender"> <layout class="org.apache.log4j.PatternLayout"> <!-- Print the date in ISO 8601 format --> <param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n"/> </layout> </appender> <logger name="com.foo"> <!-- Print only messages of level warn or above in the package com.foo --> <level value="warn"/> </logger> <root> <priority value ="debug" /> <appender-ref ref="A1" /> </root> </log4j:configuration>
Example 3
log4j.rootLogger=debug, stdout, R log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout # Pattern to output the caller's file name and line number. log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n log4j.appender.R=org.apache.log4j.RollingFileAppender log4j.appender.R.File=example.log log4j.appender.R.MaxFileSize=100KB # Keep one backup file log4j.appender.R.MaxBackupIndex=1 log4j.appender.R.layout=org.apache.log4j.PatternLayout log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"> <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"> <appender name="stdout" class="org.apache.log4j.ConsoleAppender"> <layout class="org.apache.log4j.PatternLayout"> <!-- Pattern to output the caller's file name and line number --> <param name="ConversionPattern" value="%5p [%t] (%F:%L) - %m%n"/> </layout> </appender> <appender name="R" class="org.apache.log4j.RollingFileAppender"> <param name="file" value="example.log"/> <param name="MaxFileSize" value="100KB"/> <!-- Keep one backup file --> <param name="MaxBackupIndex" value="1"/> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%p %t %c - %m%n"/> </layout> </appender> <root> <priority value ="debug" /> <appender-ref ref="stdout" /> <appender-ref ref="R" /> </root> </log4j:configuration>
Filter Configuration
Filters can be defined at appender level. For example, to filter only certain levels, the LevelRangeFilter can be used like this:
<appender name="TRACE" class="org.apache.log4j.ConsoleAppender"> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="[%t] %-5p %c - %m%n" /> </layout> <filter class="org.apache.log4j.varia.LevelRangeFilter"> <param name="levelMin" value="DEBUG" /> <param name="levelMax" value="DEBUG" /> </filter> </appender>
Advanced Topics
<yet to be described>
More examples
(Please feel free to add your own configuration examples here)
Note that TimeBasedRollingPolicy can only be configured with xml, not log4j.properties
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"> <!-- Note that this file is refreshed by the server every 60seconds, as specified in web.xml --> <log4j:configuration debug="true"> <appender name="ROLL" class="org.apache.log4j.rolling.RollingFileAppender"> <!-- The active file to log to --> <param name="file" value="/applogs/myportal/portal.log" /> <param name="append" value="true" /> <param name="encoding" value="UTF-8" /> <rollingPolicy class="org.apache.log4j.rolling.TimeBasedRollingPolicy"> <!-- The file to roll to, this is a fairly intelligent parameter, if the file ends in .gz, it gzips it, based on the date stamp it rolls at that time, default is yyyy-MM-dd, (rolls at midnight) See: http://logging.apache.org/log4j/companions/extras/apidocs/org/apache/log4j/rolling/TimeBasedRollingPolicy.html --> <param name="FileNamePattern" value="/applogs/myportal/portal.%d.log.gz" /> </rollingPolicy> <layout class="org.apache.log4j.PatternLayout"> <!-- The log message pattern --> <param name="ConversionPattern" value="%5p %d{ISO8601} [%t][%x] %c - %m%n" /> </layout> </appender> <!-- Loggers to filter out various class paths --> <logger name="org.hibernate.engine.loading.LoadContexts" additivity="false"> <level value="error"/> <appender-ref ref="ROLL" /> </logger> <!-- Debugging loggers --> <!-- Uncomment to enable debug on calpoly code only --> <!-- <logger name="edu.calpoly"> <level value="debug"/> <appender-ref ref="ROLL" /> </logger> --> <root> <priority value="info" /> <appender-ref ref="ROLL" /> </root> </log4j:configuration>
相关推荐
本讲主要介绍了Grasshopper Primer的基本应用。 Grasshopper是Rhino 3D建模软件的一个插件,它提供了一个图形化的编程环境,让设计师可以通过直观的界面创建和编辑算法,而非编写复杂的代码。这个工具使得建筑设计...
C# and XML Primer by Jonathan Hartwell English | 6 Mar. 2017 | ISBN: 1484225945 | 104 Pages | PDF | 3.17 MB Learn XML and how to use and integrate it into your C# applications using this compact book...
C# and XML Primer 英文epub 本资源转载自网络,如有侵权,请联系上传者或csdn删除 本资源转载自网络,如有侵权,请联系上传者或csdn删除
4. **地址空间**:I2C协议支持7位和10位地址,7位地址最多可连接128个从设备,10位地址则可扩展到1024个。 5. **错误处理**:I2C协议提供了一些错误检测机制,如应答错误、数据溢出错误等,以确保通信的可靠性。 **...
<title>XML Primer <author>John Doe <year>2005 ``` 在上述例子中,`<book>` 是根元素,包含了三个子元素:`<title>`、`<author>` 和 `<year>`。 XML命名规则: 1. 元素和属性名必须以字母或下划线开头。 2. ...
TinyXML入门教程 1 什么是XML? 1 文档类 2 创建文档对象 3 输出文档对象 3 保存文档对象 4 返回第一个根元素 5 声明类 5 注释类 6 元素类 6 节点名 6 父节点 6 子节点 7 编辑子节点 7 同级节点 7 遍历元素 8 元素...
Data Mining: A Tutorial-Based Primer, Second Edition (Chapman & Hall/CRC Data Mining and Knowledge Discovery Series) by Richard J. Roiger 2016 | ISBN: 1498763979 | English | 529 pages | True PDF | 32 ...
4. **Primer**: Primer是GitHub的一套设计系统,它定义了GitHub产品的视觉样式和交互规范。Doctocat采用了Primer的设计原则,确保了与GitHub平台的风格一致性,对于那些希望创建与GitHub风格一致的文档站点的人来说...
《C++ Primer》第四版是C++编程领域的一本经典教材,由Lippman, Lajoie, and Moo三位作者合著。这本书深入浅出地介绍了C++语言的基础知识、中级概念以及高级特性,旨在帮助读者掌握现代C++编程技术。源代码文件包含...
更新:2018年6月移至在OpenShift上运行在创建一个帐户创建一个PHP应用程序rhc app create primer -t php-5.4 --from-code git://github.com/eschabell/openshift-preso-openshiftprimer.git就是这样,您现在可以在...
4. 保存更改:如果进行了修改,可以使用库提供的功能将更新后的XML树写回文件。 在C++中,处理XML文件时需要注意内存管理,确保正确释放分配的内存,避免内存泄漏。此外,错误处理也是关键,因为XML文件可能存在...
这本习题解答是针对C++ Primer(第四版)教材的,旨在帮助读者巩固和深化对C++的理解。在学习C++的过程中,解决习题是提升编程技能的关键步骤,这本书提供了全面的习题解析,涵盖了从基础语法到高级特性的各个层面。...
Chapter 4 The Linux Kernel A Different Perspective Chapter 5 Kernel Initialization Chapter 6 System Initialization Chapter 7 Bootloaders Chapter 8 Device Driver Basics Chapter 9 File Systems Chapter ...
Primer Premier 5.0是一款广泛使用的分子生物学软件,主要用于设计PCR(聚合酶链式反应)引物和探针。这款软件集成了多种生物信息学工具,帮助科研人员在基因克隆、基因表达分析、SNP(单核苷酸多态性)检测等领域...
《C++ Primer:深入浅出的C++学习之路》 C++是一门强大的、高效的编程语言,被广泛应用于系统软件、游戏开发、嵌入式系统、高性能计算等多个领域。本书"cplusplus_primer"旨在为初学者提供一条清晰的学习路径,通过...
<title>XML Primer <author>Peter Murray-Rust <year>1998 ``` 在这个例子中,`<book>`是根元素,包含三个子元素:`<title>`、`<author>`和`<year>`。 二、XML解析概述 XML解析器负责读取XML文档,并将其转换...
《C++ Primer 消费税解决方案》是针对初学者的一份学习资料,主要涵盖了C++编程语言的基础知识以及如何在实际问题中应用这些知识。在这个项目中,我们可能看到的内容包括了基本语法、数据类型、控制流程、函数、类与...
《C++ Primer Plus》是Stephen Prata撰写的一本广受欢迎的C++编程教材,第六版提供了深入浅出的C++语言教程,旨在帮助初学者和有一定经验的程序员掌握这一强大的编程语言。附录中的源码文件是作者为配合书中的教学...