Introduction to Java Logging – Java日志的介绍

最后修改: 2016年 7月 11日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

Logging is a powerful aid for understanding and debugging program’s run-time behavior. Logs capture and persist the important data and make it available for analysis at any point in time.

日志是理解和调试程序运行时行为的有力助手。日志捕获并保存重要的数据,并使其在任何时间点都可用于分析。

This article discusses the most popular java logging framewloorks, Log4j 2 and Logback, along with their predecessor Log4j, and briefly touches upon SLF4J, a logging facade that provides a common interface for different logging frameworks.

本文讨论了最流行的java日志框架,Log4j 2和Logback,以及它们的前身Log4j,并简要介绍了SLF4J,一个为不同日志框架提供通用接口的日志界面。

2. Enabling Logging

2.启用日志记录功能

All the logging frameworks discussed in the article share the notion of loggers, appenders and layouts. Enabling logging inside the project follows three common steps:

文章中讨论的所有日志框架都有一个共同的概念,那就是日志者、应用者和布局。在项目内部启用日志遵循三个共同的步骤。

  1. Adding needed libraries
  2. Configuration
  3. Placing log statements

The upcoming sections discuss the steps for each framework individually.

接下来的章节将分别讨论每个框架的步骤。

3. Log4j 2

3.Log4j 2

Log4j 2 is new and improved version of the Log4j logging framework. The most compelling improvement is the possibility of asynchronous logging. Log4j 2 requires the following libraries:

Log4j 2是Log4j日志框架的新改进版本。最引人注目的改进是可以进行异步日志记录。Log4j 2需要以下库。

<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-api</artifactId>
    <version>2.6.1</version>
</dependency>
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>2.6.1</version>
</dependency>

Latest version of log4j-api you can find here and log4j-corehere.

最新版本的log4j-api你可以找到这里log4j-core这里

3.1. Configuration

3.1.配置

Configuring Log4j 2 is based on the main configuration log4j2.xml file. The first thing to configure is the appender.

配置Log4j 2是基于主配置log4j2.xml文件。首先要配置的是appender。

These determine where the log message will be routed. Destination can be a console, a file, socket, etc.

这些决定了日志信息将被传送到哪里。目的地可以是一个控制台、一个文件、套接字等。

Log4j 2 has many appenders for different purposes, you can find more information on the official Log4j 2 site.

Log4j 2有许多用于不同目的的应用程序,你可以在官方Log4j 2网站上找到更多信息。

Lets take a look at a simple config example:

让我们看一下一个简单的配置例子。

<Configuration status="debug" name="baeldung" packages="">
    <Appenders>
        <Console name="stdout" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss} %p %m%n"/>
        </Console>
    </Appenders>
</Configuration>

You can set a name for each appender, for example use name console instead of stdout.

你可以为每个appender设置一个名称,例如,使用名称console而不是stdout

Notice the PatternLayout element – this determines how message should look like. In our example, the pattern is set based on the pattern param, where %d determines date pattern, %p – output of log level, %m – output of logged message and %n – adds new line symbol. More info about pattern you can find on official Log4j 2 page.

注意PatternLayout元素–这决定了消息应该是什么样子。在我们的例子中,模式是根据pattern参数设置的,其中%d决定了日期模式,%p-输出日志级别,%m-输出日志信息,%n-添加新行符号。关于模式的更多信息,你可以在官方的Log4j 2页面找到。

Finally – to enable an appender (or multiple) you need to add it to <Root> section:

最后–要启用一个应用程序(或多个),你需要将其添加到<Root>部分。

<Root level="error">
    <AppenderRef ref="STDOUT"/>
</Root>

3.2. Logging to File

3.2.记录到文件

Sometimes you will need to use logging to a file, so we will add fout logger to our configuration:

有时你需要使用记录到一个文件,所以我们将在配置中添加fout记录器。

<Appenders>
    <File name="fout" fileName="baeldung.log" append="true">
        <PatternLayout>
            <Pattern>%d{yyyy-MM-dd HH:mm:ss} %-5p %m%nw</Pattern>
        </PatternLayout>
    </File>
</Appenders>

The File appender have several parameters that can be configured:

文件应用者有几个可以配置的参数。

  • file – determines file name of the log file
  • append – The default value for this param is true, meaning that by default a File appender will append to an existing file and not truncate it.
  • PatternLayout that was described in previous example.

In order to enable File appender you need to add it to <Root> section:

为了启用文件应用程序,你需要将其添加到<Root>部分。

<Root level="INFO">
    <AppenderRef ref="stdout" />
    <AppenderRef ref="fout"/>
</Root>

3.3. Asynchronous Logging

3.3.异步日志记录

If you want to make your Log4j 2 asynchronous you need to add LMAX disruptor library to your pom.xml. LMAX disruptor is a lock-free inter-thread communication library.

如果你想让你的Log4j 2成为异步的,你需要在你的pom.xml中添加LMAX disruptor库。LMAX disruptor是一个无锁线程间通信库。

Adding disruptor to pom.xml:

将disruptor添加到pom.xml中。

<dependency>
    <groupId>com.lmax</groupId>
    <artifactId>disruptor</artifactId>
    <version>3.3.4</version>
</dependency>

Latest version of disruptor can be found here.

最新版本的干扰器可以在这里找到。

If you want to use LMAX disruptor you need to use <asyncRoot> instead of <Root> in your configuration.

如果你想使用LMAX干扰器,你需要在配置中使用<asyncRoot>而不是<Root>

<AsyncRoot level="DEBUG">
    <AppenderRef ref="stdout" />
    <AppenderRef ref="fout"/>
</AsyncRoot>

Or you can enable asynchronous logging by setting the system property Log4jContextSelector to org.apache.logging.log4j.core.async.AsyncLoggerContextSelector.

或者你可以通过设置系统属性Log4jContextSelectororg.apache.logging.log4j.core.async.AsyncLoggerContextSelector来启用异步日志。

You can of course read more about the configuration of the Log4j2 async logger and see some performance diagrams on the Log4j2 official page .

当然,你可以在Log4j2官方网页上阅读更多关于Log4j2异步记录器的配置,并看到一些性能图示。

3.4. Usage

3.4.使用方法

The following is a simple example that demonstrates the use of Log4j for logging:

下面是一个简单的例子,演示了Log4j在日志方面的应用。

import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;

public class Log4jExample {

    private static Logger logger = LogManager.getLogger(Log4jExample.class);

    public static void main(String[] args) {
        logger.debug("Debug log message");
        logger.info("Info log message");
        logger.error("Error log message");
    }
}

After running, the application will log the following messages to both console and file named baeldung.log:

运行后,应用程序将在控制台和名为baeldung.log的文件中记录以下信息:

2016-06-16 17:02:13 INFO  Info log message
2016-06-16 17:02:13 ERROR Error log message

If you elevate the root log level to ERROR:

如果你将根日志级别提升到ERROR

<level value="ERROR" />

The output will look like the following:

输出结果将看起来像下面这样。

2016-06-16 17:02:13 ERROR Error log message

As you can see, changing the log level to upper parameter causes the messages with lower log levels will not be print to appenders.

正如你所看到的,将日志级别改为上层参数会导致较低日志级别的信息不会被打印到应用者。

Method logger.error can be also used to log an exception that occurred:

方法logger.error也可以用来记录一个发生的异常。

try {
    // Here some exception can be thrown
} catch (Exception e) {
    logger.error("Error log message", throwable);
}

3.5. Package Level Configuration

3.5.包级配置

Let’s say you need to show messages with the log level TRACE – for example from a specific package such as com.baeldung.log4j2:

假设你需要显示日志级别为TRACE的消息–例如来自一个特定的包,如com.baeldung.log4j2

logger.trace("Trace log message");

For all other packages you want to continue logging only INFO messages.

对于所有其他软件包,你想继续只记录INFO信息。

Keep in mind that TRACE is lower than the root log level INFO that we specified in configuration.

请记住,TRACE比我们在配置中指定的根日志级别INFO低。

To enable logging only for one of packages you need to add the following section before <Root> to your log4j2.xml:

要想只对其中一个包启用日志,你需要在你的<Root>中的log4j2.xml前添加以下部分。

<Logger name="com.baeldung.log4j2" level="debug">
    <AppenderRef ref="stdout"/>
</Logger>

It will enable logging for com.baeldung.log4j package and your output will look like:

它将启用com.baeldung.log4j包的日志,你的输出将看起来像。

2016-06-16 17:02:13 TRACE Trace log message
2016-06-16 17:02:13 DEBUG Debug log message
2016-06-16 17:02:13 INFO  Info log message
2016-06-16 17:02:13 ERROR Error log message

4. Logback

4.回程

Logback is meant to be an improved version of Log4j, developed by the same developer who made Log4j.

Logback旨在成为Log4j的改进版,由制作Log4j的同一个开发者开发。

Logback also has a lot more features compared to Log4j, with many of them being introduced into Log4j 2 as well. Here’s a quick look at all of the advantages of Logback on the official site.

与Log4j相比,Logback还拥有更多的功能,其中许多功能也被引入到Log4j 2中。下面是在官方网站上对Logback的所有优点的简要介绍。

Let’s start by adding the following dependency to the pom.xml:

让我们先在pom.xml中加入以下依赖关系。

<dependency>
    <groupId>ch.qos.logback</groupId>
    <artifactId>logback-classic</artifactId>
    <version>1.2.6</version>
</dependency>

This dependency will transitively pull in another two dependencies, the logback-core and slf4j-api. Note that the latest version of Logback can be found here.

这一依赖关系将过渡性地拉入另外两个依赖关系,即logback-coreslf4j-api。请注意,Logback 的最新版本可以在这里找到。

4.1. Configuration

4.1.配置

Let’s now have a look at a Logback configuration example:

现在让我们来看看一个Logback配置的例子。

<configuration>
  # Console appender
  <appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
    <layout class="ch.qos.logback.classic.PatternLayout">
      # Pattern of log message for console appender
      <Pattern>%d{yyyy-MM-dd HH:mm:ss} %-5p %m%n</Pattern>
    </layout>
  </appender>

  # File appender
  <appender name="fout" class="ch.qos.logback.core.FileAppender">
    <file>baeldung.log</file>
    <append>false</append>
    <encoder>
      # Pattern of log message for file appender
      <pattern>%d{yyyy-MM-dd HH:mm:ss} %-5p %m%n</pattern>
    </encoder>
  </appender>

  # Override log level for specified package
  <logger name="com.baeldung.log4j" level="TRACE"/>

  <root level="INFO">
    <appender-ref ref="stdout" />
    <appender-ref ref="fout" />
  </root>
</configuration>

Logback uses SLF4J as an interface, so you need to import SLF4J’s Logger and LoggerFactory.

Logback使用SLF4J作为接口,所以你需要导入SLF4J的LoggerLoggerFactory。

4.2. SLF4J

4.2.SLF4J

SLF4J provides a common interface and abstraction for most of the Java logging frameworks. It acts as a facade and provides standardized API for accessing the underlying features of the logging framework.

SLF4J为大多数Java日志框架提供了一个通用接口和抽象。它作为一个门面,为访问日志框架的底层功能提供标准化的API。

Logback uses SLF4J as native API for its functionality. Following is the example using Logback logging:

Logback使用SLF4J作为其功能的本地API。以下是使用Logback日志的例子。

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Log4jExample {

    private static Logger logger = LoggerFactory.getLogger(Log4jExample.class);

    public static void main(String[] args) {
        logger.debug("Debug log message");
        logger.info("Info log message");
        logger.error("Error log message");
    }
}

The output will remain the same as in previous examples.

输出将保持与前面的例子相同。

5. Log4J

5.Log4J

Finally, let’s have a look at the venerable Log4j logging framework.

最后,让我们看一下古老的Log4j日志框架。

At this point it’s of course outdated, but worth discussing as it lays the foundation for its more modern successors.

在这一点上,它当然已经过时,但值得讨论,因为它为其更现代的继任者奠定了基础。

Many of the configuration details match those discussed in Log4j 2 section.

许多配置细节与Log4j 2章节中讨论的一致。

5.1. Configuration

5.1.配置

First of all you need to add Log4j library to your projects pom.xml:

首先,你需要将Log4j库添加到你的项目pom.xml中:

<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>

Here you should be able to find latest version of Log4j.

在这里你应该能够找到最新版本的Log4j。

Lets take a look at a complete example of simple Log4j configuration with only one console appender:

让我们看看一个简单的Log4j配置的完整例子,只有一个控制台应用者。

<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd" >
<log4j:configuration debug="false">

    <!--Console appender-->
    <appender name="stdout" class="org.apache.log4j.ConsoleAppender">
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" 
              value="%d{yyyy-MM-dd HH:mm:ss} %p %m%n" />
        </layout>
    </appender>

    <root>
        <level value="INFO" />
        <appender-ref ref="stdout" />
    </root>

</log4j:configuration>

<log4j:configuration debug=”false”> is open tag of whole configuration which has one property – debug. It determines whether you want to add Log4j debug information to logs.

<log4j:configuration debug=”false”>是整个配置的开放标签,它有一个属性 – debug。它决定了你是否要在日志中添加Log4j的调试信息。

5.2. Usage

5.2.使用方法

After you have added Log4j library and configuration you can use logger in your code. Lets take a look at a simple example:

在你添加了Log4j库和配置后,你就可以在你的代码中使用记录器。让我们看一下一个简单的例子。

import org.apache.log4j.Logger;

public class Log4jExample {
    private static Logger logger = Logger.getLogger(Log4jExample.class);

    public static void main(String[] args) {
        logger.debug("Debug log message");
        logger.info("Info log message");
        logger.error("Error log message");
    }
}

6. Conclusion

6.结论

This article shows very simple examples of how you can use different logging framework such as Log4j, Log4j2 and Logback. It covers simple configuration examples for all of the mentioned frameworks.

这篇文章展示了非常简单的例子,说明如何使用不同的日志框架,如Log4j、Log4j2和Logback。它涵盖了所有提到的框架的简单配置例子。

The examples that accompany the article can be found over on GitHub.

文章所附的例子可以在GitHub上找到