How to use log4j to record logs in Java
1. Preface
log4j is a reliable, fast and flexible logging framework (API) written in Java, which is released under the Apache Software License. Log4j has been ported to languages such as C, C++, C#, Perl, Python and Ruby.
Log4j is highly configurable and can be configured through external files at runtime. It prioritizes logging and provides mechanisms to direct logging information to many destinations, such as databases, files, consoles, UNIX system logs, etc.
There are three main components in Log4j:
Loggers: Responsible for capturing logging information.
Appenders: Responsible for publishing log information to different preferred destinations.
Layouts: Responsible for formatting log information in different styles.
Note: This article is based on log4j 2.X and above.
2. Installation
log4j-core-xx.jar
log4j-api-xx.jar
log4j-web -xx.jar (required reference for web projects)
3. Configuration
Prepare some log classes and add the following references:
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger;
static Logger logger = LogManager.getLogger(Test.class.getName());
The configuration file location is in: src root directory , even if there is no configuration file, no error will be reported, and the output will be in the form of console by default.
The log4j2 configuration file is very different from log4 (the 1. ):
<?xml version="1.0" encoding="UTF-8"?> <configuration status="error"> <!--先定义所有的appender--> <appenders> <!--这个输出控制台的配置--> <Console name="Console" target="SYSTEM_OUT"> <!--这个是输出日志的格式--> <PatternLayout pattern="%d{HH:mm:ss.SSS} %-5level %class{36} %L %M - %msg%xEx%n"/> </Console> <!--文件会打印出所有信息,这个log每次运行程序会自动清空,由append属性决定,适合临时测试用--> <File name="Error" fileName="${web:rootDir}/logs/error.log" append="false"> <!--文件只记录level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch)--> <ThresholdFilter level="error" onMatch="ACCEPT" onMismatch="DENY"/> <PatternLayout charset="UTF-8" pattern="%d{HH:mm:ss.SSS} %-5level %class{36} %L %M - %msg%xEx%n"/> </File> <!--这个会打印出所有的信息,每次大小超过size,则这size大小的日志会自动存入按年份-月份建立的文件夹下面并进行压缩,作为存档--> <RollingFile name="RollingFile" fileName="${web:rootDir}/logs/history.log" filePattern="log/$${date:yyyy-MM}/history-%d{MM-dd-yyyy}-%i.log.gz"> <PatternLayout charset="UTF-8" pattern="%d{yyyy-MM-dd 'at' HH:mm:ss z} %-5level %class{36} %L %M - %msg%xEx%n"/> <SizeBasedTriggeringPolicy size="50MB"/> </RollingFile> </appenders> <!--然后定义logger,只有定义了logger并引入的appender,appender才会生效--> <loggers> <!--建立一个默认的root的logger--> <root level="trace"> <appender-ref ref="Error"/> <appender-ref ref="RollingFile"/> <appender-ref ref="Console"/> </root> </loggers> </configuration>
4. Ordinary projects and web projects
For ordinary projects, it can be used normally after the above configuration is completed. For web projects, no log files will be generated. of. You need to add the following configuration under the root node of
For more related articles on how to use log4j to record logs under Java, please pay attention to the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

Start Spring using IntelliJIDEAUltimate version...

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

When using TKMyBatis for database queries, how to gracefully get entity class variable names to build query conditions is a common problem. This article will pin...
