search
HomeJavajavaTutorialHow 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 &#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>

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
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
What aspects of Java development are platform-dependent?What aspects of Java development are platform-dependent?Apr 26, 2025 am 12:19 AM

Javadevelopmentisnotentirelyplatform-independentduetoseveralfactors.1)JVMvariationsaffectperformanceandbehavioracrossdifferentOS.2)NativelibrariesviaJNIintroduceplatform-specificissues.3)Filepathsandsystempropertiesdifferbetweenplatforms.4)GUIapplica

Are there performance differences when running Java code on different platforms? Why?Are there performance differences when running Java code on different platforms? Why?Apr 26, 2025 am 12:15 AM

Java code will have performance differences when running on different platforms. 1) The implementation and optimization strategies of JVM are different, such as OracleJDK and OpenJDK. 2) The characteristics of the operating system, such as memory management and thread scheduling, will also affect performance. 3) Performance can be improved by selecting the appropriate JVM, adjusting JVM parameters and code optimization.

What are some limitations of Java's platform independence?What are some limitations of Java's platform independence?Apr 26, 2025 am 12:10 AM

Java'splatformindependencehaslimitationsincludingperformanceoverhead,versioncompatibilityissues,challengeswithnativelibraryintegration,platform-specificfeatures,andJVMinstallation/maintenance.Thesefactorscomplicatethe"writeonce,runanywhere"

Explain the difference between platform independence and cross-platform development.Explain the difference between platform independence and cross-platform development.Apr 26, 2025 am 12:08 AM

Platformindependenceallowsprogramstorunonanyplatformwithoutmodification,whilecross-platformdevelopmentrequiressomeplatform-specificadjustments.Platformindependence,exemplifiedbyJava,enablesuniversalexecutionbutmaycompromiseperformance.Cross-platformd

How does Just-In-Time (JIT) compilation affect Java's performance and platform independence?How does Just-In-Time (JIT) compilation affect Java's performance and platform independence?Apr 26, 2025 am 12:02 AM

JITcompilationinJavaenhancesperformancewhilemaintainingplatformindependence.1)Itdynamicallytranslatesbytecodeintonativemachinecodeatruntime,optimizingfrequentlyusedcode.2)TheJVMremainsplatform-independent,allowingthesameJavaapplicationtorunondifferen

Why is Java a popular choice for developing cross-platform desktop applications?Why is Java a popular choice for developing cross-platform desktop applications?Apr 25, 2025 am 12:23 AM

Javaispopularforcross-platformdesktopapplicationsduetoits"WriteOnce,RunAnywhere"philosophy.1)ItusesbytecodethatrunsonanyJVM-equippedplatform.2)LibrarieslikeSwingandJavaFXhelpcreatenative-lookingUIs.3)Itsextensivestandardlibrarysupportscompr

Discuss situations where writing platform-specific code in Java might be necessary.Discuss situations where writing platform-specific code in Java might be necessary.Apr 25, 2025 am 12:22 AM

Reasons for writing platform-specific code in Java include access to specific operating system features, interacting with specific hardware, and optimizing performance. 1) Use JNA or JNI to access the Windows registry; 2) Interact with Linux-specific hardware drivers through JNI; 3) Use Metal to optimize gaming performance on macOS through JNI. Nevertheless, writing platform-specific code can affect the portability of the code, increase complexity, and potentially pose performance overhead and security risks.

What are the future trends in Java development that relate to platform independence?What are the future trends in Java development that relate to platform independence?Apr 25, 2025 am 12:12 AM

Java will further enhance platform independence through cloud-native applications, multi-platform deployment and cross-language interoperability. 1) Cloud native applications will use GraalVM and Quarkus to increase startup speed. 2) Java will be extended to embedded devices, mobile devices and quantum computers. 3) Through GraalVM, Java will seamlessly integrate with languages ​​such as Python and JavaScript to enhance cross-language interoperability.

See all articles

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

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use