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

AI Hentai Generator
Generate AI Hentai for free.

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



Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

This article explores integrating functional programming into Java using lambda expressions, Streams API, method references, and Optional. It highlights benefits like improved code readability and maintainability through conciseness and immutability

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

This article explains Java's NIO API for non-blocking I/O, using Selectors and Channels to handle multiple connections efficiently with a single thread. It details the process, benefits (scalability, performance), and potential pitfalls (complexity,

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

This article details Java's socket API for network communication, covering client-server setup, data handling, and crucial considerations like resource management, error handling, and security. It also explores performance optimization techniques, i
