如何部署和搭建测试log4j 2

来源:互联网 发布:golang与java哪个好 编辑:程序博客网 时间:2024/05/22 01:45

官方地址:http://logging.apache.org/log4j/2.x/manual/configuration.html

翻译官网原文有助于理解


Apache Log4j 2 is an upgrade to Log4j that provides significant improvements over its predecessor, Log4j 1.x, and provides many of the improvements available in Logback while fixing some inherent problems in Logback's architecture.

Apache Log4j 2是一个Log4j的升级,提供了比他的前身Log4j 1.x更重大的改进,并且它提供了在Logback中可用的许多改进,同时,修复了很多在Logback的结构中的一些内部问题。

Log4j 2 API

Overview

The Log4j 2 API provides the interface that applications should code to and provides the adapter components required for implementers to create a logging implementation. Although Log4j 2 is broken up between an API and an implementation, the primary purpose of doing so was not to allow multiple implementations, although that is certainly possible, but to clearly define what classes and methods are safe to use in "normal" application code.

Log4j 2 API提供应用程序可以编写代码的接口并且为实施者提供了创建一个日志实现所需的适配器组件。尽管log4j 2是打破了一个API和一个实现这种关系,这样做的主要目的是不允许多个接口的实现,尽管这当然是可能的,但要清楚的定义类和方法被用在正常的应用程序代码中是安全的。

Hello World!

No introduction would be complete without the customary Hello, World example. Here is ours. First, a Logger with the name "HelloWorld" is obtained from theLogManager. Next, the logger is used to write the "Hello, World!" message, however the message will be written only if the Logger is configured to allow informational messages.
没有通俗易懂的hello world例子就不能称为一个完整的介绍。这是我们的(没明白这里什么意思)。首先,一个名为“Hello world”的Logger是从LogManager来获得的。其次,Logger被用来写“hello,world”消息,然而这个消息仅仅是在Logger配置了允许消息记录信息的时候才能打印出来。

import org.apache.logging.log4j.LogManager;import org.apache.logging.log4j.Logger;public class HelloWorld  {private static final Logger logger = LogManager.getLogger("HelloWorld");public static void main(String[] args) {logger.info("Hello, World!");}}

这里我是在一个空的工程中搭建的该类,首先的问题就是LogManager和Logger这两个类没有,下载了官网上的zip文件,里面有很多的jar包,尝试了一下,log4j-api-2.0.2.jar这个jar包里面是有这两个类的,引入之后运行,发现还需要引入log4j-core-2.0.2.jar这个类,引入这两个类之后发现还是会报错,报错信息如下:
ERROR StatusLogger No log4j2 configuration file found. Using default configuration: logging only errors to the console.
该错误的意思应该是没有找到配置文件,使用了默认的配置文件,只有error级别的错误可以在控制台打印,这时往下读文档。

The output from the call to logger.info() will vary significantly depending on the configuration used. See theConfiguration section for more details.
调用logger.info()进行输入将会很大程度的依赖配置的使用。更多细节详见配置一章。

从这里可以看出,我们需要的配置的内容应该在这个配置章节中,所以跳转到配置章节进行学习。

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%的代码是致力于logging的。因此,甚至一个适中大小的应用都会有数以千记的logging块嵌入他们的代码中。由于他们的数量,不用手动修改他们变得十分重要了。

Configuration of Log4j 2 can be accomplished in 1 of 4 ways:
配置log4j 2可以用下面1到4方式来配置:

  1. Through a configuration file written in XML, JSON, or YAML.
  2. Programmatically, by creating a ConfigurationFactory and Configuration implementation.
  3. Programmatically, by calling the APIs exposed in the Configuration interface to add components to the default configuration.
  4. Programmatically, by calling methods on the internal Logger class.
1.通过写一个XML,JSON或者YAML文件来进行配置
2.通过编程的方式,通过创建一个ConfigurationFactory类和Configuration接口实现类来配置。
3.通过编程的方式,通过调用暴露在Configuration接口中的API,添加组件到默认的配置中。
4.通过编程的方式,通过调用在Logger类内部的方法来实现。

This page focuses primarily on configuring Log4j through a configuration file. Information on programmatically configuring Log4j can be found atExtending Log4j 2.
这页主要是通过一个配置文件来配置log4j。通过编程的方式来实现的信息可以在Extending Log4j 2这个链接中找到。

这里我只先学习通过XML,JSON或者YAML配置文件来进行配置的方式,通过编程来实现的方式暂时还用不到,所以这里不点击链接进去学习了,以后有需要再去看

Automatic Configuration

Log4j has the ability to automatically configure itself during initialization. When Log4j starts it will locate all the ConfigurationFactory plugins and arrange then in weighted order from highest to lowest. As delivered, Log4j contains two ConfigurationFactory implementations, one for JSON and one for XML.
Log4j有能力在它初始化期间进行自动配置。当Log4j开始时,它将会部署所有的ConfigurationFactory插件并且按照按照权重进行从高到低的排序。当交付的时候,Log4j包含两个显示ConfigurationFactory接口的实现类,一个对应JSON,一个对应XML。

  1. Log4j will inspect the "log4j.configurationFile" system property and, if set, will attempt to load the configuration using theConfigurationFactory that matches the file extension.
  2. If no system property is set the JSON ConfigurationFactory will look for log4j2-test.json or log4j2-test.jsn in the classpath.
  3. If no such file is found the XML ConfigurationFactory will look for log4j2-test.xml in the classpath.
  4. If a test file cannot be located the JSON ConfigurationFactory will look for log4j2.json or log4j2.jsn on the classpath.
  5. If a JSON file cannot be located the XML ConfigurationFactory will try to locate log4j2.xml on the classpath.
  6. If no configuration file could be located the DefaultConfiguration will be used. This will cause logging output to go to the console.
1.Log4j将会检查“log4j.configurationFile”系统属性,如果设置了,就会尝试去加载使用匹配ConfigurationFactory的文件扩展名的配置。
2.如果没有设置系统属性,那么JSON ConfigurationFactory将会在类路径中查找 log4j2-test.json or log4j2-test.jsn .
3.如果没有这样的文件,那么XML ConfigurationFactory 会在类路径中寻找 log4j2-test.xml .
4.如果一个测试文件不能定位,那么JSON ConfigurationFactory 会寻找log4j2.json or log4j2.jsn
5.如果一个JSON文件不能定位,那么XMLConfigurationFactory就会在类路径中尝试定位log4j2.xml .
6.如果没有定位配置文件,DefaultConfiguration将会启用。这些将会引起日志输出到控制台上。

看了上面关于配置的加载顺序,了解了log4j加载的优先级

An example application named MyApp that uses log4j can be used to illustrate how this is done.
一个使用了log4j的名为MyApp的应用实例可以用于说明这些是怎么工作的。

下面是官网上给的例子:
import com.foo.Bar; // Import log4j classes.import org.apache.logging.log4j.Logger;import org.apache.logging.log4j.LogManager; public class MyApp { // Define a static logger variable so that it references the// Logger instance named "MyApp".static final Logger logger = LogManager.getLogger(MyApp.class.getName()); public static void main(String[] args) { // Set up a simple configuration that logs on the console. logger.trace("Entering application.");Bar bar = new Bar();if (!bar.doIt()) {  logger.error("Didn't do it.");}logger.trace("Exiting application.");                 }}

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);  }}

这里我在自己的工程中也创建同样的类

MyApp begins by importing log4j related classes. It then defines a static logger variable with the nameMyApp which happens to be the fully qualified name of the class.
导入log4j相关的类,然后用MyApp这个名称定义一个logger静态变量,这个名称是类的完全限定名称。

Log4j will provide a default configuration if it cannot locate a configuration file. The default configuration, provided in the DefaultConfiguration class, will set up:
  • A ConsoleAppender attached to the root logger.
  • A PatternLayout set to the pattern "%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" attached to the ConsoleAppender

Note that by default Log4j assigns the root logger to Level.ERROR.

如果log4j没有定位到一个配置文件的话,那么它就将会提供一个默认的配置文件。在DefaultConfiguration这个类中提供的默认配置将会建立如下内容:
一个ConsoleAppender将会附加到跟日志中
一个PatternLayout设置模式"%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" 附加到ConsoleAppender中。
值得注意的是:通过默认Log4j分配的跟日志级别为error。

这里是说明默认的情况下显示日志的格式是怎么定义的和日志显示的级别。

所以这里我的结果和官网显示基本一致
ERROR StatusLogger No log4j2 configuration file found. Using default configuration: logging only errors to the console.16:16:10.765 [main] ERROR com.foo.Bar - Did it again!16:16:10.765 [main] ERROR com.foo.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将会首先尝试从配置文件去配置。默认的配置样式为:
<?xml version="1.0" encoding="UTF-8"?><Configuration status="WARN">  <Appenders>    <Console name="Console" target="SYSTEM_OUT">      <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>    </Console>  </Appenders>  <Loggers>    <Root level="error">      <AppenderRef ref="Console"/>    </Root>  </Loggers></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文件替换,你会得到和上面的列表同样的结果。改变根的等级为trace会返回以下结果。

这里也就是说,需要我们的classpath中自己定义一个xml文件,用来配置log4j,然后改变log的级别,就可以显示其他内容了。

把上面xml的内容复制到工程中,按照上面说的文件名称部署,确实打印出了两个信息,而且没有了红色的警告了。这时修改log的级别为trace,就把所有的信息打印出来了。

17:13:01.540 [main] TRACE MyApp - Entering application.17:13:01.540 [main] TRACE com.foo.Bar - entry17: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.

至此,已经能够使用log4j2了,以后有了新的需求再去学习怎么使用,目前先到这里了


1 0
原创粉丝点击