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

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)

Hot Topics

Java Tutorial
1662
14
PHP Tutorial
1261
29
C# Tutorial
1234
24
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 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 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 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...

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 to use the Redis cache solution to efficiently realize the requirements of product ranking list? How to use the Redis cache solution to efficiently realize the requirements of product ranking list? Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

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

See all articles