Log4j – Configuring Log4j 2 - Apache Log4j 2
Posted 近博
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Log4j – Configuring Log4j 2 - Apache Log4j 2相关的知识,希望对你有一定的参考价值。
Configuration
Inserting log requests into the application code requires a fair amount of planning and effort. Observation shows that approximately 4 percent of code is dedicated to logging. Consequently, even moderately sized applications will have thousands of logging statements embedded within their code. Given their number, it becomes imperative to manage these log statements without the need to modify them manually.(在应用程序代码中插入日志需要大量的计划和努力。观察表明,约百分之4的代码专门用于日志管理。因此,即使是中等大小的应用程序也会有成千上万的日志语句嵌入到它们的代码中。考虑到它们的数量,就必须对这些日志语句进行管理,而不需要手工修改代码。)
Configuration of Log4j 2 can be accomplished in 1 of 4 ways:(配置Log4j 2可以使用下面4个方法中的一个来完成:)
- Through a configuration file written in XML, JSON, YAML, or properties format.(通过一个XML, JSON, YAML, 或properties 格式的配置文件)
- Programmatically, by creating a ConfigurationFactory and Configuration implementation.(以编程方式)
- Programmatically, by calling the APIs exposed in the Configuration interface to add components to the default configuration.(以编程方式)
- Programmatically, by calling methods on the internal Logger class.(以编程方式)
This page focuses primarily on configuring Log4j through a configuration file. Information on programmatically configuring Log4j can be found at Extending Log4j 2 and Programmatic Log4j Configuration.(这个章节的焦点是通过配置文件来配置Log4j。通过编程方式来配置Log4j的相关信息可以在Extending Log4j 2 和Programmatic Log4j Configuration 中找到。)
Note that unlike Log4j 1.x, the public Log4j 2 API does not expose methods to add, modify or remove appenders and filters or manipulate the configuration in any way.(请注意,与log4j 1.x不同,log4j 2 的Public API没有公开用来添加、修改或删除appender和filters或以任何方式操纵配置的方法)
Automatic Configuration(自动配置)
Log4j has the ability to automatically configure itself during initialization. When Log4j starts it will locate all the ConfigurationFactory plugins and arrange them in weighted order from highest to lowest. As delivered, Log4j contains four ConfigurationFactory implementations: one for JSON, one for YAML, one for properties, and one for XML.(log4j具有在初始化过程中自动配置自身的能力。当log4j启动就会找到所有的configurationfactory插件和安排他们在从最高到最低的加权进行排序。log4j包含四种ConfigurationFactory 实现:一个JSON,一个YAML,一个properties,和一个XML。)
- Log4j will inspect the "log4j.configurationFile" system property and, if set, will attempt to load the configuration using the ConfigurationFactory that matches the file extension.(log4j将检查 "log4j.configurationFile" 系统属性,如果设置了这个属性,将尝试使用匹配这个文件扩展名的 ConfigurationFactory 加载配置。)
- If no system property is set the properties ConfigurationFactory will look for log4j2-test.properties in the classpath.(如果"log4j.configurationFile"系统属性没有被设置,properties ConfigurationFactory 就会去查找classpath 中的 log4j2-test.properties )
- If no such file is found the YAML ConfigurationFactory will look for log4j2-test.yaml or log4j2-test.yml in the classpath.(如果上面的文件都没有找到,YAML ConfigurationFactory 就会去查找classpath 中的log4j2-test.yaml 或log4j2-test.yml )
- If no such file is found the JSON ConfigurationFactory will look for log4j2-test.json or log4j2-test.jsn in the classpath.(如果上面的文件都没有找到,JSON ConfigurationFactory 就会去查找classpath 中的 log4j2-test.json or log4j2-test.jsn)
- If no such file is found the XML ConfigurationFactory will look for log4j2-test.xml in the classpath.(如果上面的文件都没有找到,XML ConfigurationFactory 就会去查找classpath 中的log4j2-test.xml)
- If a test file cannot be located the properties ConfigurationFactory will look for log4j2.properties on the classpath.(如果找不到测试文件,properties ConfigurationFactory 就会去查找classpath 中的 log4j2.properties )
- If a properties file cannot be located the YAML ConfigurationFactory will look for log4j2.yaml or log4j2.yml on the classpath.(如果找不到 properties 文件,YAML ConfigurationFactory 就会去查找classpath 中的 log4j2.yaml or log4j2.yml )
- If a YAML file cannot be located the JSON ConfigurationFactory will look for log4j2.json or log4j2.jsn on the classpath.(如果找不到 YAML 文件, JSON ConfigurationFactory 就会去查找classpath 中的 log4j2.json or log4j2.jsn )
- If a JSON file cannot be located the XML ConfigurationFactory will try to locate log4j2.xml on the classpath.(如果找不到 JSON 文件, XML ConfigurationFactory 就会去查找classpath 中的 log4j2.xml )
- If no configuration file could be located the DefaultConfiguration will be used. This will cause logging output to go to the console.(如果找不到任何配置文件, 就会使用 DefaultConfiguration 。它会将日志输出在控制台中 )
An example application named MyApp that uses log4j can be used to illustrate how this is done.(一个使用log4j 的例子,可以用来说明Log4j的自动配置是如何完成的。)
1 import com.foo.Bar; 2 3 // Import log4j classes. 4 import org.apache.logging.log4j.Logger; 5 import org.apache.logging.log4j.LogManager; 6 7 public class MyApp { 8 9 // Define a static logger variable so that it references the 10 // Logger instance named "MyApp". 11 private static final Logger logger = LogManager.getLogger(MyApp.class); 12 13 public static void main(final String... args) { 14 15 // Set up a simple configuration that logs on the console. 16 17 logger.trace("Entering application."); 18 Bar bar = new Bar(); 19 if (!bar.doIt()) { 20 logger.error("Didn\'t do it."); 21 } 22 logger.trace("Exiting application."); 23 } 24 }
MyApp begins by importing log4j related classes. It then defines a static logger variable with the name MyApp which happens to be the fully qualified name of the class.(MyApp通过导入log4j相关的类开始。然后使用了MyApp的全限定类名定义了一个静态的日志记录器。)
MyApp uses the Bar class defined in the packagecom.foo.
package com.foo; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.LogManager; public class Bar { static final Logger logger = LogManager.getLogger(Bar.class.getName()); public boolean doIt() { logger.entry(); logger.error("Did it again!"); return logger.exit(false); } }
Log4j will provide a default configuration if it cannot locate a configuration file. The default configuration, provided in the DefaultConfiguration class, will set up:(Log4j在找不到配置文件的时候,提供了一个默认的配置。默认配置由DefaultConfiguration 类提供,会建立:)
- A ConsoleAppender attached to the root logger.(为root logger添加一个ConsoleAppender )
- A PatternLayout set to the pattern "%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" attached to the ConsoleAppender(为ConsoleAppender 添加一个模式为"%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" 的PatternLayout )
Note that by default Log4j assigns the root logger to Level.ERROR.(注意root logger 的默认级别为 Level.ERROR)
The output of MyApp would be similar to:
17:13:01.540 [main] ERROR com.foo.Bar - Did it again! 17:13:01.540 [main] ERROR MyApp - Didn\'t do it.
As was described previously, Log4j will first attempt to configure itself from configuration files. A configuration equivalent to the default would look like:(正如上面描述的那样,Log4j首先会尝试从配置文件中读取配置。和默认配置等价的配置文件如下:)
1 <?xml version="1.0" encoding="UTF-8"?> 2 <Configuration status="WARN"> 3 <Appenders> 4 <Console name="Console" target="SYSTEM_OUT"> 5 <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/> 6 </Console> 7 </Appenders> 8 <Loggers> 9 <Root level="error"> 10 <AppenderRef ref="Console"/> 11 </Root> 12 </Loggers> 13 </Configuration>
Once the file above is placed into the classpath as log4j2.xml you will get results identical to those listed above. Changing the root level to trace will result in results similar to:(一旦上面的文件被命名为log4j2.xml并放在classpath 下,你就会得到和上面的输出结果等价的结果。将 root level 修改为trace会得到类似如下的结果:)
17:13:01.540 [main] TRACE MyApp - Entering application. 17:13:01.540 [main] TRACE com.foo.Bar - entry 17:13:01.540 [main] ERROR com.foo.Bar - Did it again! 17:13:01.540 [main] TRACE com.foo.Bar - exit with (false) 17:13:01.540 [main] ERROR MyApp - Didn\'t do it. 17:13:01.540 [main] TRACE MyApp - Exiting application.
Note that status logging is disabled when the default configuration is used.(如果提供了默认的level 则 Configuration 节点中的status 无效)
Additivity(附加性)
Perhaps it is desired to eliminate all the TRACE output from everything except com.foo.Bar. Simply changing the log level would not accomplish the task. Instead, the solution is to add a new logger definition to the configuration:(也许你想让所有的Trace级别的日志都不输出,除了com.foo.bar。仅仅更改日志级别将无法达到你的目的。相反,解决方法是添加一个新的日志记录器定义:)
1 <Logger name="com.foo.Bar" level="TRACE"/> 2 <Root level="ERROR"> 3 <AppenderRef ref="STDOUT"> 4 </Root>
With this configuration all log events from com.foo.Bar will be recorded while only error events will be recorded from all other components. (使用这个配置,所有的来自于com.foo.Bar 包下的日志事件都会被记录,然而其它包下的只有error级别的日志事件会被记录。)
In the previous example all the events from com.foo.Bar were still written to the Console. This is because the logger for com.foo.Bar did not have any appenders configured while its parent did. In fact, the following configuration(在先前的例子中,所有的来自于 com.foo.Bar 包下的事件仍然会写入到Console 。这是因为 com.foo.Bar 的日志记录器没有配置任何的appenders 然而它的父元素Root 却配置了。实际上,它的配置如下: )
1 <?xml version="1.0" encoding="UTF-8"?> 2 <Configuration status="WARN"> 3 <Appenders> 4 <Console name="Console" target="SYSTEM_OUT"> 5 <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/> 6 </Console> 7 </Appenders> 8 <Loggers> 9 <Logger name="com.foo.Bar" level="trace"> 10 <AppenderRef ref="Console"/> 11 </Logger> 12 <Root level="error"> 13 <AppenderRef ref="Console"/> 14 </Root> 15 </Loggers> 16 </Configuration>
would result in
17:13:01.540 [main] TRACE com.foo.Bar - entry 17:13:01.540 [main] TRACE com.foo.Bar - entry 17:13:01.540 [main] ERROR com.foo.Bar - Did it again! 17:13:01.540 [main] TRACE com.foo.Bar - exit (false) 17:13:01.540 [main] TRACE com.foo.Bar - exit (false) 17:13:01.540 [main] ERROR MyApp - Didn\'t do it.
Notice that the trace messages from com.foo.Bar appear twice. This is because the appender associated with logger com.foo.Bar is first used, which writes the first instance to the Console. Next, the parent of com.foo.Bar, which in this case is the root logger, is referenced. The event is then passed to its appender, which is also writes to the Console, resulting in the second instance. This is known as additivity. While additivity can be quite a convenient feature (as in the first previous example where no appender reference needed to be configured), in many cases this behavior is considered undesirable and so it is possible to disable it by setting the additivity attribute on the logger to false:(注意,来自于 com.foo.Bar 包下的日志出现了两次。这是因为和com.foo.Bar 日志记录器相关的appender 被第一次使用时,它会将第一个实例写到控制台。接下来又被com.foo.Bar 的父级--root logger 引用。然后当事件被传递给root logger的appender时,它也会将信息写入到控制台,这就导致了两次输出。这就是所谓的附加性。然而additivity 可以是一个相当方便的功能(正如在先前的第一个例子中,他不需要配置 AppenderRef 而是直接使用root logger 的AppenderRef ),在许多情况下,这种行为被视为不受欢迎的,并且很可能通过设置additivity 属性值为false将它禁用 。)
1 <?xml version="1.0" encoding="UTF-8"?> 2 <Configuration status="WARN"> 3 <Appenders> 4 <Console name="Console" target="SYSTEM_OUT"> 5 <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/> 6 </Console> 7 </Appenders> 8 <Loggers> 9 <Logger name="com.foo.Bar" level="trace" additivity="false"> 10 <AppenderRef ref="Console"/> 11 </Logger> 12 <Root level="error"> 13 <AppenderRef ref="Console"/> 14 </Root> 15 </Loggers> 16 </Configuration>
Once an event reaches a logger with its additivity set to false the event will not be passed to any of its parent loggers, regardless of their additivity setting.(一旦一个事件传递到一个additivity属性值为false的logger ,这个事件就不会再被传递到它的父loggers )
Automatic Reconfiguration(自动重新配置)
When configured from a File, Log4j has the ability to automatically detect changes to the configuration file and reconfigure itself. If the monitorInterval attribute is specified on the configuration element and is set to a non-zero value then the file will be checked the next time a log event is evaluated and/or logged and the monitorInterval has elapsed since the last check. The example below shows how to configure the attribute so that the configuration file will be checked for changes only after at least 30 seconds have elapsed. The minimum interval is 5 seconds.(当从配置文件中读取配置时,log4j具有自动检测配置文件变化和重新配置自身的能力。如果在配置元素上指定 monitorInterval 属性并且它的值为非0,则日志文件会在下一次的日志事件评估/日志记录并且经过monitorinterval设置的时间后被重新检查。下面的示例演示如何配置属性,以便在至少30秒之后检查配置文件的更改。最小间隔为5秒。)
1 <?xml version="1.0" encoding="UTF-8"?> 2 <Configuration monitorInterval="30"> 3 ... 4 </Configuration>
Chainsaw can automatically process your log files (Advertising appender configurations)(Chainsaw能够自动处理你的日志文件(通知 appender 配置))
Log4j provides the ability to \'advertise\' appender configuration details for all file-based appenders as well as socket-based appenders. For example, for file-based appenders, the file location and the pattern layout in the file are included in the advertisement. Chainsaw and other external systems can discover these advertisements and use that information to intelligently process the log file.(log4j提供了为所有基于文件以及基于Socket的appenders ‘宣传’ appender的配置细节的能力 。例如,基于文件的appender,它们的文件位置和pattern layout都被包含在”广告“中。Chainsaw 和其他外部系统可以发现这些”广告“并使用这些信息智能化地处理日志文件)
The mechanism by which an advertisement is exposed, as well as the advertisement format, is specific to each Advertiser implementation. An external system which would like to work with a specific Advertiser implementation must understand how to locate the advertised configuration as well as the format of the advertisement. For example, a \'database\' Advertiser may store configuration details in a database table. An external system can read that database table in order to discover the file location and the file format.(针对每个广告商实现 都有其广告暴露的机制,以及这个广告的格式。要与特定的广告商实现一起工作的外部系统必须了解如何定位广告配置以及广告格式。例如,“数据库”广告商可以将配置细节存储在数据库表中。外部系统可以读取数据库表以发现文件位置和文件格式。)
Log4j provides one Advertiser implementation, a \'multicastdns\' Advertiser, which advertises appender configuration details via IP multicast using the http://jmdns.sourceforge.net library.(Log4j提供了一个广告商实现---\'multicastdns\' Advertiser 它会通过使用 http://jmdns.sourceforge.net 库的IP广播对appender的配置细节进行广告)
Chainsaw automatically discovers log4j\'s multicastdns-generated advertisements and displays those discovered advertisements in Chainsaw\'s Zeroconf tab (if the jmdns library is in Chainsaw\'s classpath). To begin parsing and tailing a log file provided in an advertisement, just double-click the advertised entry in Chainsaw\'s Zeroconf tab. Currently, Chainsaw only supports FileAppender advertisements.(Chainsaw 自动发现Log4j的multicastdns生成的广告并且会在 Chainsaw\'s Zeroconf tab 展示那些被发现的广告(如果jmdnslibrary 在Chainsaw的 classpath)。开始解析并且跟踪在广告中提供的日志文件,只要在Chainsaw的Zeroconf tab 中双击广告记录。目前,Chainsaw 只支持FileAppender广告。)
To advertise an appender configuration:(为了广告一个appender 的配置:)
- Add the JmDns library from http://jmdns.sourceforge.net to the application classpath(从 http://jmdns.sourceforge.net 将JmDns库添加到应用程序的classpath中)
- Set the \'advertiser\' attribute of the configuration element to \'multicastdns\'(设置configuration 元素的‘advertiser ’属性值为 \'multicastdns\')
- Set the \'advertise\' attribute on the appender element to \'true\'(设置appender 元素的‘advertiser ’属性值为 \'true\')
- If advertising a FileAppender-based configuration, set the \'advertiseURI\' attribute on the appender element to an appropriate URI(如果广告一个基于FileAppender 的配置,设置 appender 元素的‘advertiseURI’属性值为 一个合适的URI )
FileAppender-based configurations require an additional \'advertiseURI\' attribute to be specified on the appender. The \'advertiseURI\' attribute provides Chainsaw with information on how the file can be accessed. For example, the file may be remotely accessible to Chainsaw via ssh/sftp by specifying a Commons VFS (http://commons.apache.org/proper/commons-vfs/) sftp:// URI, an http:// URI may be used if the file is accessible through a web server, or a file:// URI can be specified if accessing the file from a locally-running instance of Chainsaw.(基于FileAppender 的配置需要指定一个额外的 \'advertiseURI\' 。\'advertiseURI\' 将如何去访问文件的信息提供给Chainsaw。例如,文件可能要Chainsaw 通过 ssh/sftp 进行远程访问,通过指定一个通用的VFS (http://commons.apache.org/proper/commons-vfs/) sftp:// URI ,如果文件可以通过web 服务器访问可以使用 http:// URI,如果可以通过本地允许的Chainsaw 实例来访问文件则可以使用file:// URI )
Here is an example advertisement-enabled appender configuration which can be used by a locally-running Chainsaw to automatically tail the log file (notice the file:// advertiseURI):(这是一个激活了广告的appender配置,它可以使用本地允许的Chainsaw 来自动跟踪日志文件 (注意使用 file:// advertiseURI))
Please note, you must add the JmDns library from http://jmdns.sourceforge.net to your application classpath in order to advertise with the \'multicastdns\' advertiser.(请注意,你一定要从http://jmdns.sourceforge.net 将JmDns 库添加到你的应用程序中的classpath ,这样才能够成功使用 \'multicastdns\' 进行广告。 )
1 <?xml version="1.0" encoding="UTF-8"?> 2 <Configuration advertiser="multicastdns"> 3 ... 4 </Configuration> 5 <Appenders> 6 <File name="File1" fileName="output.log" bufferedIO="false" advertiseURI="file://path/to/output.log" advertise="true"> 7 ... 8 </File> 9 </Appenders>
Configuration Syntax(配置语法)
As the previous examples have shown as well as those to follow, Log4j allows you to easily redefine logging behavior without needing to modify your application. It is possible to disable logging for certain parts of the application, log only when specific criteria are met such as the action being performed for a specific user, route output to Flume or a log reporting system, etc. Being able to do this requires understanding the syntax of the configuration files.(如前面的例子所显示的那样,Log4j允许您轻松地重新定义记录行为,而不需要修改应用程代码。可以禁用应用程序的某些部分的日志,日志只有当特定条件满足才会将日志信息输出到Flume 或日志报告系统等。要能够做到这一点需要去了解配置文件的语法。)
The configuration element in the XML file accepts several attributes:(在XML文件中的配置元素接受的几个属性:)
Attribute Name | Description |
---|---|
log4j的使用步骤 |