Home > Java > javaTutorial > Using Log4j2 for log management in Java API development

Using Log4j2 for log management in Java API development

王林
Release: 2023-06-18 17:28:59
Original
1796 people have browsed it

Java API is a widely used programming language. Due to its simplicity, reliability, cross-platform and other advantages, it has become a mainstream language in the field of enterprise development. In Java API development, log management is an integral part. During the development process, we usually use Log4j2 (an upgraded version of Log4j) to manage logs because it has the following advantages:

  1. High efficiency: Log4j2 uses asynchronous log printing, so that the output of the log does not have IO blocking , thereby ensuring efficient execution of the build tool.
  2. Easy to use: Log4j2 provides flexible configuration functions that can dynamically modify the log level, output format, and output location without restarting the application.
  3. Rich interfaces: Log4j2 provides various log APIs, including SLF4J, Apache Commons Logging, etc., which can be selected according to actual needs.

This article will introduce how to use Log4j2 for log management during Java API development.

Step one: Import Log4j2 related dependencies

First, we need to import Log4j2 dependencies in the project.

Maven dependency:

<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>2.14.1</version>
</dependency>
Copy after login

Gradle dependency:

implementation 'org.apache.logging.log4j:log4j-core:2.14.1'
Copy after login

Step 2: Configure Log4j2

Before using Log4j2 for log management, we need to first configure it. Log4j2 supports multiple configuration methods, including XML, JSON, YAML or Properties, etc.

The following is an example of a basic Log4j2 configuration file:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="INFO">
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
        </Console>
        <RollingFile name="RollingFile" fileName="logs/app.log"
                     filePattern="logs/app-%d{yyyy-MM-dd}-%i.log.gz">
            <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss,SSS} [%t] %-5level %logger{36} - %msg%n"/>
            <Policies>
                <TimeBasedTriggeringPolicy />
                <SizeBasedTriggeringPolicy size="10MB" />
            </Policies>
        </RollingFile>
    </Appenders>
    <Loggers>
        <Root level="info">
            <AppenderRef ref="Console"/>
            <AppenderRef ref="RollingFile"/>
        </Root>
    </Loggers>
</Configuration>
Copy after login

This configuration file defines two Appenders: Console and RollingFile.

Console Appender outputs logs to the console and uses PatternLayout to format the output content.

RollingFile Appender outputs the log to a file and uses PatternLayout to format the output content. In addition, it also configures two Policies: TimeBasedTriggeringPolicy and SizeBasedTriggeringPolicy.

TimeBasedTriggeringPolicy means rolling the log file according to time. In this example, it means creating a new log file every day and compressing the previous log files.

SizeBasedTriggeringPolicy means rolling the log file according to the file size. In this example, it means that when the log file size reaches 10 MB, a new log file will be created.

The above is only a Log4j2 configuration based on a simple example. In actual situations, we need to configure it according to our needs.

Step 3: Use Log4j2 for log management

After configuring Log4j2, we need to use it in the code for log management. The following is a basic Log4j2 log management example:

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

public class App {

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

    public static void main(String[] args) {
        logger.info("Hello, Log4j2!");
    }
}
Copy after login

In the above code, we first imported the Logger class related to Log4j2 and obtained a Logger instance through LogManager.

Then, in the main method, we use logger to output an info level log message.

Through the above operations, we can use Log4j2 for log management.

Summary

The above is the entire process of using Log4j2 for log management in Java API development. To use Log4j2 for log management, we need to configure it first, instantiate the Logger class in the code, and use it for log management.

By using Log4j2, we can perform log management efficiently, flexibly, and richly, which brings great convenience to debugging and troubleshooting during the Java API development process.

The above is the detailed content of Using Log4j2 for log management in Java API development. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template