Home Java javaTutorial Very detailed Log4j configuration steps

Very detailed Log4j configuration steps

Jan 18, 2017 pm 12:47 PM

1. Configuration file
The basic format of the Log4J configuration file is as follows:

#配置根Logger 
log4j.rootLogger = [ level ] , appenderName1 , appenderName2 , … 
#配置日志信息输出目的地Appender 
log4j.appender.appenderName = fully.qualified.name.of.appender.class 
  log4j.appender.appenderName.option1 = value1 
  … 
  log4j.appender.appenderName.optionN = valueN 
#配置日志信息的格式(布局) 
log4j.appender.appenderName.layout = fully.qualified.name.of.layout.class 
  log4j.appender.appenderName.layout.option1 = value1 
  … 
  log4j.appender.appenderName.layout.optionN = valueN
Copy after login

where [level] is the log output level, there are 5 levels in total:

FATAL 0 
ERROR 3 
WARN 4 
INFO 6 
DEBUG 7
Copy after login

Appender is the purpose of log output Log4j provides the following appenders:

org.apache.log4j.ConsoleAppender(控制台), 
org.apache.log4j.FileAppender(文件), 
org.apache.log4j.DailyRollingFileAppender(每天产生一个日志文件), 
org.apache.log4j.RollingFileAppender(文件大小到达指定尺寸的时候产生一个新的文件), 
org.apache.log4j.WriterAppender(将日志信息以流格式发送到任意指定的地方) 
Layout:日志输出格式,Log4j提供的layout有以下几种: 
org.apache.log4j.HTMLLayout(以HTML表格形式布局), 
org.apache.log4j.PatternLayout(可以灵活地指定布局模式), 
org.apache.log4j.SimpleLayout(包含日志信息的级别和信息字符串), 
org.apache.log4j.TTCCLayout(包含日志产生的时间、线程、类别等等信息)
Copy after login

Print parameters: Log4J uses a printing format similar to the printf function in C language to format log information, as follows:

  %m 输出代码中指定的消息 
  %p 输出优先级,即DEBUG,INFO,WARN,ERROR,FATAL 
  %r 输出自应用启动到输出该log信息耗费的毫秒数 
  %c 输出所属的类目,通常就是所在类的全名 
  %t 输出产生该日志事件的线程名 
  %n 输出一个回车换行符,Windows平台为“\r\n”,Unix平台为“\n” 
  %d 输出日志时间点的日期或时间,默认格式为ISO8601,也可以在其后指定格式,比如:%d{yyy MMM dd HH:mm:ss , SSS},输出类似:2002年10月18日 22 : 10 : 28 , 921 
  %l 输出日志事件的发生位置,包括类目名、发生的线程,以及在代码中的行数。举例:Testlog4.main(TestLog4.java: 10 )
Copy after login
2. Initialize Logger in code :
1) Call the BasicConfigurator.configure() method in the program: add a ConsoleAppender to the root recorder, and set the output format to "%-4r [%t] %-5p %c %x - %m% through PatternLayout n", and the default level of the root logger is Level.DEBUG.
2) The configuration is placed in the file, the file name is passed through the command line parameters, and it is parsed and configured through PropertyConfigurator.configure(args[x]);
3) The configuration is placed in the file, and the file name and other information is passed through environment variables, and the log4j default initialization process is used to parse and configure it;
4) The configuration is placed in the file, and the file name and other information is passed through the application server configuration. Configuration is accomplished using a special servlet.
3. Set log output levels for different Appenders:
When debugging the system, we often pay attention to only the exception level log output, but usually all levels of output are placed in one file. If the log The output level is BUG! ? Then go find it slowly.
At this time we may want to be able to output the exception information to a file separately. Of course, Log4j already provides such a function. We only need to modify the Appender's Threshold in the configuration to achieve it, such as the following example:

[Configuration file]

### set log levels ### 
log4j.rootLogger = debug , stdout , D , E 
### 输出到控制台 ### 
log4j.appender.stdout = org.apache.log4j.ConsoleAppender 
log4j.appender.stdout.Target = System.out 
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout 
log4j.appender.stdout.layout.ConversionPattern = %d{ABSOLUTE} %5p %c{ 1 }:%L - %m%n 
### 输出到日志文件 ### 
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender 
log4j.appender.D.File = logs/log.log 
log4j.appender.D.Append = true 
log4j.appender.D.Threshold = DEBUG ## 输出DEBUG级别以上的日志 
log4j.appender.D.layout = org.apache.log4j.PatternLayout 
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n 
### 保存异常信息到单独文件 ### 
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender 
log4j.appender.D.File = logs/error.log ## 异常日志文件名 
log4j.appender.D.Append = true 
log4j.appender.D.Threshold = ERROR ## 只输出ERROR级别以上的日志!!! 
log4j.appender.D.layout = org.apache.log4j.PatternLayout 
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n 
[代码中使用] 
public class TestLog4j { 
public static void main(String[] args) { 
PropertyConfigurator.configure( " D:/Code/conf/log4j.properties " ); 
Logger logger = Logger.getLogger(TestLog4j. class ); 
logger.debug( " debug " ); 
logger.error( " error " ); 
} 
}
Copy after login

Run it, Check whether the exception information is saved in a separate file error.log

For more detailed Log4j configuration steps related articles, 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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

How does Java's classloading mechanism work, including different classloaders and their delegation models? How does Java's classloading mechanism work, including different classloaders and their delegation models? Mar 17, 2025 pm 05:35 PM

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

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache? How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache? Mar 17, 2025 pm 05:44 PM

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

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading? How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading? Mar 17, 2025 pm 05:43 PM

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]

How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution? How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution? Mar 17, 2025 pm 05:46 PM

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

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management? How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management? Mar 17, 2025 pm 05:45 PM

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

See all articles