A Guide to Log4j and the log4j.properties File in Java – Java 中的 Log4j 和 log4j.properties 文件指南

最后修改: 2023年 9月 26日

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

1. Introduction

1.导言

Log4J is a popular, open-source logging framework written in Java. Various Java-based applications widely use Log4j. Moreover, it’s thread-safe, fast, and provides a named Logger hierarchy. Log4j is distributed under the open-source Apache Software License.

Log4J 是一个流行的开源 日志框架,使用 Java 编写。各种基于 Java 的应用程序广泛使用 Log4j。此外,Log4j 线程安全、速度快,并提供命名的 Logger 层次结构。Log4j 采用开源的 Apache 软件许可证发布。

Log4j 1.x reached the end of life on August 5, 2015. Therefore, as of today, Log4j2 is the latest upgrade to Log4j.

Log4j 1.x 于 2015 年 8 月 5 日寿终正寝。因此,从今天开始,Log4j2 是 Log4j 的最新升级版本。

In this tutorial, we’ll learn about Log4j and how to configure the core Log4j components using the log4j.properties file in Java.

在本教程中,我们将了解 Log4j 以及如何使用 Java 中的 log4j.properties 文件配置 Log4j 核心组件。

2. Maven Setup

2.Maven 设置

We’ll need the log4j-core dependency in our pom.xml to start with:

首先,我们需要在 pom.xml 中加入 log4j-core 依赖关系:

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

The latest version of log4j-core can be found here.

log4j-core 的最新版本可在此处找到。

3. The Log4j API

3.Log4j API

The Log4j API provides the mechanism to pass on the logging information based on various levels of priorities and direct it to various destinations such as files, consoles, databases, etc. It also supports filtering log events before passing them to loggers or appenders.

Log4j API 提供了一种机制,可根据不同的优先级传递日志信息,并将其导向文件、控制台、数据库等不同的目的地。它还支持在将日志事件传递给 loggers 或 appenders 之前对其进行过滤。

The Log4j API has a layered architecture that provides two types of objects in the Log4j framework – core objects and support objects.

Log4j API 采用分层架构,在 Log4j 框架中提供两类对象–核心对象和支持对象。

4. Log4j Components

4.Log4j 组件

There are three main components of Log4j – loggers, appenders, and layouts – that could be used together to print the customized log statements at the desired destinations. Let’s look at them in brief.

Log4j 有三个主要组件 – 日志记录器应用程序布局,它们可以一起使用,以便在所需的目的地打印自定义日志语句。让我们简单了解一下它们。

4.1. Logger

4.1. 记录仪</em

The Logger object is responsible for representing the logging information. It’s the first mandatory layer in Log4j architecture. The Logger class is defined in package org.apache.log4j.

Logger 对象负责表示日志信息。它是 Log4j 架构中的第一个强制层。Logger 类定义在包 org.apache.log4j 中。

Generally, we create one Logger instance per application class to log important events belonging to that class. Also, we generally create this instance at the beginning of the class using a static factory method that accepts the class name as a parameter:

通常,我们为每个应用程序类创建一个 Logger 实例,以记录属于该类的重要事件。此外,我们通常在类的开头使用静态工厂方法创建该实例,该方法接受类名作为参数:

private static final Logger logger = Logger.getLogger(JavaClass.class.getName());

Subsequently, we can use various methods of the Logger class to log or print important events depending on their categories. These methods are trace(), debug(), info(), warn(), error(), fatal(). These methods determine the level of a logging request.

随后,我们可以根据重要事件的类别,使用 Logger 类的各种方法来记录或打印重要事件。这些方法是 trace()debug()info()warn()error()fatal()。这些方法可确定日志记录请求的级别。

The priority order of the Logger methods is: TRACE < DEBUG < INFO < WARN < ERROR < FATAL. Therefore, these methods print the log messages depending on the logger level set in the log4j.properties file. This means if we set the logger level as INFO, then all the INFO, WARN, ERROR, and FATAL events will be logged.

Logger 方法的优先级顺序为TRACE < DEBUG < INFO < WARN < ERROR < FATAL.因此,这些方法打印日志信息取决于 log4j.properties 文件中设置的 logger 级别。这意味着,如果我们将 logger 级别设置为 INFO,那么所有的 INFOWARNERRORFATAL 事件都将被记录。

4.2. Appender

4.2. 添加剂</em

Appender denotes the destination of log output. We can print the log out to multiple preferred destinations using Log4j like console, files, remote socket server, database, etc. We refer to these output destinations as Appenders. Moreover, we can attach multiple appenders to a Logger.

Appender 表示日志输出的目的地。我们可以使用 Log4j 将日志打印到多个首选目的地,如控制台、文件、远程套接字服务器、数据库等。我们将这些输出目的地称为 Appender。此外,我们还可以将多个 Appenders 附加到一个 Logger 上。

Appenders work according to the appender additivity rule. This rule states that the output of a log statement of any Logger will go to all of its appenders and its ancestors – the appenders that are higher in the hierarchy.

Appenders 根据 appender additivity 规则 工作。该规则规定,任何 Logger 的日志语句的输出都将发送到其所有 appender 及其祖先 – 层次结构中较高的 appender

Log4j has multiple appenders defined for files, consoles, GUI components, remote socket servers, JMS, etc.

Log4j 为文件、控制台、图形用户界面组件、远程套接字服务器、JMS 等定义了多个 appenders。

4.3. Layout

4.3 布局</em

We use layouts for customizing the format of the log statements. We can do this by associating a layout with the already defined appender. Thus, a combination of layout and appenders helps us send the formatted log statements to the desired destinations.

我们使用 布局自定义日志语句的格式。我们可以将 layout 与已定义的 appender 关联起来。因此,结合使用 layoutappenders 可以帮助我们将格式化的日志语句发送到所需的目的地。

We can specify the format of log statements using conversion patterns. The class PatternLayout explains more about conversion characters that we can use based on our needs.

我们可以使用转换模式指定日志语句的格式。PatternLayout类解释了有关转换字符的更多信息,我们可以根据需要使用这些字符。

We’ll also understand about few of the conversion characters through examples in the following sections.

在下面的章节中,我们还将通过示例了解一些转换字符。

5. The log4j.properties File

5.log4j.properties 文件

We can configure Log4j using XML or the properties file. The log4j.properties file stores the configurations in key-value pairs.

我们可以使用 XML 或属性文件配置 Log4j。log4j.properties 文件以键值对的形式存储配置。

The default name of the log4j properties configuration file is log4j.properties. The Logger looks for this file name in the CLASSPATH. However, if we need to use a different configuration file name, we can set it using the system property log4j.configuration.

log4j 属性配置文件的默认名称是 log4j.propertiesLogger 会在 CLASSPATH 中查找此文件名。但是,如果我们需要使用不同的配置文件名,可以使用系统属性 log4j.configuration 进行设置。

The log4j.properties file contains the specifications of appenders, their names and types, and layout patterns. It also contains specifications about the default root Logger and its log levels.

log4j.properties 文件包含应用程序的规格、名称和类型以及布局模式。它还包含有关默认 root 日志记录器及其日志级别的规范。

6. Syntax of the log4j.properties File

6.log4j.properties 文件的语法

In a general log4j.properties file, we define the following configurations:

在一般的 log4j.properties 文件中,我们定义了以下配置:

  • The root logger and its level. We also provide a name for the appender here.
  • Then, we assign a valid appender to the defined appender name.
  • Finally, we define the layout, target, level, etc., for the defined appender.

Let’s see the syntax of a general log4.properties file:

让我们看看一般 log4.properties 文件的语法:

# The root logger with appender name 
log4j.rootLogger = DEBUG, NAME
  
# Assign NAME a valid appender  
log4j.appender.NAME = org.apache.log4j.FileAppender

# Define the layout for NAME
log4j.appender.NAME.layout=org.apache.log4j.PatternLayout  
log4j.appender.NAME.layout.conversionPattern=%m%n  

Here, NAME is the name of the Appender. As discussed earlier, we can attach multiple appenders to a Logger to direct logs to different destinations.

这里,NAMEAppender 的名称。如前所述,我们可以为日志记录器附加多个应用程序,以便将日志导向不同的目的地。

7. Examples

7.实例

Now, let’s understand the log4j.properties file configurations for different appenders with the help of some examples.

现在,让我们借助一些示例来了解不同 appenderlog4j.properties 文件配置。

7.1. Sample Program

7.1.程序样本

Let’s start with an example application that logs some messages:

让我们从一个记录一些信息的应用程序示例开始:

import org.apache.log4j.Logger;

public class Log4jExample {

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

    public static void main(String[] args) throws InterruptedException {
        for(int i = 1; i <= 2000; i++) {
            logger.info("This is the " + i + " time I say 'Hello World'.");
            Thread.sleep(100);
        }
    }
}

The application is a simple one – it writes some messages in a loop, with a short delay between iterations. It has 2,000 iterations, and there’s a pause of 100 ms in each iteration. Therefore, it should take around three and a half minutes to finish the execution. We’ll use this application in our examples below.

这是一个简单的应用程序–它在一个循环中写入一些信息,迭代之间有短暂的延迟。它有 2,000 次迭代,每次迭代暂停 100 毫秒。因此,完成执行大约需要三分半钟。我们将在下面的示例中使用此应用程序。

7.2. Console Logging

7.2.控制台日志

The console is the default place for logging messages if no configuration file is located. Let’s create a log4j.properties configuration for ConsoleAppender with the root logger and also define the logging level for it:

如果没有配置文件,控制台是记录消息的默认位置。让我们使用 root 日志记录器ConsoleAppender 创建 log4j.properties 配置,并为其定义日志记录级别:

# Root Logger
log4j.rootLogger=INFO, stdout

# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

Here, we’ve defined a log4j.properties file with the following specifications:

在这里,我们定义了一个 log4j.properties 文件,其规格如下:

  • We’ve defined the level of the root logger as INFO. This means that all the log events with level INFO and above will be logged. We’ve also defined a name for the appender as stdout.
  • Since we want to direct the logs to the console, we assigned the Appender as org.apache.log4j.ConsoleAppender and the target as System.out.
  • Finally, we’ve specified the format for PatternLayout in which we want to print the logs using ConversionPattern.

Let’s also understand the meaning of each of the conversion characters in the ConversionPattern that we’ve used:

我们还要了解我们使用的 ConversionPattern 中每个转换字符的含义:

  • %d adds the timestamp in the defined format.
  • %-5p adds the log-level information to each log statement. It signifies that the priority of the logging event should be left justified to a width of five characters.
  • %c{1} prints the qualified class name, optionally followed by package names (precision qualifier), that is, logging the specific log statement.
  • %L prints the line number of the specific log event.
  • %m prints the actual log message.
  • %n adds a new line after every log statement.

Thus, when we run our sample application, we get the following lines printed on the console:

因此,当我们运行示例应用程序时,控制台上会打印出以下几行:

2023-08-01 00:27:25 INFO Log4jExample:15 - This is the 1 time I say 'Hello World'.
...
...
2023-08-01 00:27:25 INFO Log4jExample:15 - This is the 2000 time I say 'Hello World'.

The documentation for the PatternLayout class explains more about conversion characters that we can use based on our needs.

PatternLayout类的文档介绍了更多有关转换字符的信息,我们可以根据需要使用这些字符。

7.3. Multiple Destinations

7.3.多个目的地

As discussed earlier, we can redirect the log events to multiple destinations:

如前所述,我们可以将日志事件重定向到多个目的地:

# Root logger  
log4j.rootLogger=INFO, file, stdout  
  
# Direct to a file
log4j.appender.file=org.apache.log4j.RollingFileAppender  
log4j.appender.file.File=C:\\Baeldung\\app.log  
log4j.appender.file.MaxFileSize=5KB  
log4j.appender.file.MaxBackupIndex=2  
log4j.appender.file.layout=org.apache.log4j.PatternLayout  
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n  
   
# Direct to console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender  
log4j.appender.stdout.Target=System.out  
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout  
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n  

Here, we’ve used two appenders to redirect the log messages to both the file and console. Also, we’ve assigned a RollingFileAppender to our file Appender. We use a RollingFileAppender when we know that the log files may grow in size over time.

在这里,我们使用了两个 appender 将日志信息重定向到文件和控制台。此外,我们还为文件 Appender 指定了 RollingFileAppender 。当我们知道日志文件的大小可能会随着时间的推移而增大时,我们就会使用 RollingFileAppender

In our example above, we’ve used RollingFileAppender, which rolls the log files based on both size and the count of log files using the MaxFileSize and the MaxBackupIndex parameters. Thus, the log file will roll when its size reaches 5KB, and we’ll keep a maximum of two rolled log files as backup.

在上面的示例中,我们使用了RollingFileAppender,它使用MaxFileSizeMaxBackupIndex参数根据日志文件的大小和数量来滚动日志文件。

When we run our sample application, we obtain the following files containing the same log statements as in the previous example:

运行示例应用程序时,我们会得到以下文件,其中包含与上一示例中相同的日志语句:

31/01/2023  10:28    138 app.log
31/01/2023  10:28  5.281 app.log.1
31/01/2023  10:28  5.281 app.log.2

We can find a detailed explanation of the execution in our examples on rolling log files based on size.

我们可以在根据文件大小滚动日志文件的示例中找到详细的执行说明。

8. Conclusion

8.结论

In this article, we’ve explored Log4j and its three components – loggers, appenders, and layouts. We’ve also understood the syntax of a log4j.properties file and some simple examples of configuring a log4j.properties file.

在本文中,我们探讨了 Log4j 及其三个组件 – 记录器应用程序布局。我们还了解了 log4j.properties 文件的语法以及配置 log4j.properties 文件的一些简单示例。

As always, the examples that accompany the article are available over on GitHub.

与往常一样,本文附带的示例可在 GitHub 上获取