Home Java javaTutorial How to use log4j to record logs in Java

How to use log4j to record logs in Java

Jan 18, 2017 am 11:54 AM

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;
Copy after login
static Logger logger = LogManager.getLogger(Test.class.getName());
Copy after login

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 &#39;at&#39; 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>
Copy after login

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 in web. The content can be of certain help to everyone's study or work. If you have any questions, you can leave a message to communicate. Thank you for your support to the PHP Chinese website.

For more related articles on how to use log4j to record logs under Java, please pay attention to the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

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. ...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

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...

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

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...

How do I convert names to numbers to implement sorting and maintain consistency in groups? How do I convert names to numbers to implement sorting and maintain consistency in groups? Apr 19, 2025 pm 11:30 PM

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

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

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...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? Apr 19, 2025 pm 11:27 PM

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...

How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? Apr 19, 2025 pm 09:51 PM

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...

See all articles