The integration and configuration of the Apache Log4J Web framework in the Java class library
Apache Log4j is a powerful framework for logging. Its integration and configuration in the Java class library is very important.In this article, we will discuss how to integrate log4j into the web framework of the Java application and demonstrate how to perform basic configuration.
First, let's add log4j to our Java project through Maven.In the `pom.xml` file, add the following dependencies:
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.14.1</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-web</artifactId>
<version>2.14.1</version>
</dependency>
Next, we need to create a log4j2 configuration file in the root directory of the project.Create a file called `log4j2.xml`, and add the following content to it:
<?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>
<File name="File" fileName="logs/application.log">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
</File>
</Appenders>
<Loggers>
<Root level="info">
<AppenderRef ref="Console"/>
<AppenderRef ref="File"/>
</Root>
</Loggers>
</Configuration>
In the above configuration files, we define two APPENDER (Console and File), which output the log into a log file called the console and a log file called the `Application. Log`.`Pattern` elements define the format of the log message.
After completing the configuration, we can start using LOG4J in the code.In the class that needs to record the log, first import the log 4J log:
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
Then, create a logger instance:
private static final Logger logger = LogManager.getLogger(YourClassName.class);
When you need to record the log, you can use the following methods to record the log messages of different levels through logger:
logger.trace("This is a trace message.");
logger.debug("This is a debug message.");
logger.info("This is an info message.");
logger.warn("This is a warn message.");
logger.error("This is an error message.");
logger.fatal("This is a fatal message.");
In the default configuration, messages that are lower than equal to INFO levels will be exported to console and log files.However, you can control the output level of the log by changing the `level` attribute of the root logger in the configuration file.
The above is the basic configuration and usage of Apache Log4J into the Java class library.Using log4j, we can easily record and manage the logs of the application to help us get better visualization and debug ability when developing and eliminating problems.