Home Java javaTutorial How to use Log4j to output logs of different Packages to different files

How to use Log4j to output logs of different Packages to different files

Jan 18, 2017 pm 12:42 PM

Preface

As the scale of the project becomes larger and larger, new modules will be continuously introduced, and different modules will print their own logs. In the end, the logs cannot be viewed at all, such as my own In the project, there are the following logs:

Logs for receiving external messages and logs for sending external messages;

Processing logs of background resident threads;

External interface access Interface logs such as parameters and return results;

SQL logs generated by Service accessing the database;

Among them, the amount of log data in the message log and background thread is very large. If all logs are printed in one In the file, if you use tail -f log.log file, you will find that the log is scrolling rapidly, and it is impossible to view or even locate a specific SQL or Service access log.

The solution is to classify and output different logs so that mutual logs do not affect each other. Especially the important interface access logs can easily locate and troubleshoot problems.

Step 1: Configure in log4j.properties

First post all my own log4j.properties configuration:

log4j.rootLogger=INFO, console, file
  
log4j.appender.console=net.czt.log.AsyncConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%d [%t] %-5p crazyant-web %-17c{2} (%13F:%L) %X{USER_ID}|%X{USER_IP}|%X{SERVER_ADDRESS}|%X{SERVER_NAME}|%X{REQUEST_URI}|%X{SESSION_ID} - %m%n
log4j.appender.console.bufferSize=10000
log4j.appender.console.encoding=UTF-8
  
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.file=/home/work/apache-tomcat-6.0.39/logs/crazyant.log
log4j.appender.file.MaxBackupIndex=5
log4j.appender.file.MaxFileSize=1GB
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%-5p] crazyant-web %d{yyyy-MM-dd HH:mm:ss,SSS} %X{USER_ID}|%X{USER_IP}|%X{SERVER_ADDRESS}|%X{SERVER_NAME}|%X{REQUEST_URI}|%X{SESSION_ID} method:%l%n%m%n
log4j.appender.file.bufferSize=10000
log4j.appender.file.encoding=UTF-8
  
log4j.logger.net.czt.crazyant.msg=DEBUG, message
log4j.additivity.net.czt.crazyant.msg=false
log4j.appender.message=org.apache.log4j.RollingFileAppender
log4j.appender.message.File=/home/work/apache-tomcat-6.0.39/logs/crazyant_message.log
log4j.appender.message.Append=true
log4j.appender.message.MaxFileSize=1GB
log4j.appender.message.MaxBackupIndex=5
log4j.appender.message.layout=org.apache.log4j.PatternLayout
log4j.appender.message.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} [%-5p][%c{1}] [%t] - %m%n
log4j.appender.message.encoding=UTF-8
  
log4j.logger.net.czt.crazyant.async.service=DEBUG, async
log4j.additivity.net.czt.crazyant.async.service=false
log4j.appender.async=org.apache.log4j.RollingFileAppender
log4j.appender.async.File=/home/work/apache-tomcat-6.0.39/logs/crazyant_async.log
log4j.appender.async.Append=true
log4j.appender.async.MaxFileSize=1GB
log4j.appender.async.MaxBackupIndex=5
log4j.appender.async.layout=org.apache.log4j.PatternLayout
log4j.appender.async.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} [%-5p][%c{1}] [%t] - %m%n
log4j.appender.async.encoding=UTF-8
  
log4j.logger.net.czt.orm.mybatis.SqlMonitorManager=DEBUG, showsql
log4j.additivity.net.czt.orm.mybatis.SqlMonitorManager=false
log4j.logger.net.czt.transaction.interceptor.SmartTransactionInterceptor=DEBUG, showsql
log4j.additivity.net.czt.transaction.interceptor.SmartTransactionInterceptor=false
log4j.appender.showsql=org.apache.log4j.RollingFileAppender
log4j.appender.showsql.File=/home/work/apache-tomcat-6.0.39/logs/crazyant_sql.log
log4j.appender.showsql.Append=true
log4j.appender.showsql.MaxFileSize=1GB
log4j.appender.showsql.MaxBackupIndex=5
log4j.appender.showsql.layout=org.apache.log4j.PatternLayout
log4j.appender.showsql.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} [%-5p][%c{1}] [%t] - %m%n
log4j.appender.showsql.encoding=UTF-8
  
log4j.logger.net.czt.crazyant.service=DEBUG, service
log4j.additivity.net.czt.crazyant.service=false
log4j.appender.service=org.apache.log4j.RollingFileAppender
log4j.appender.service.File=/home/work/apache-tomcat-6.0.39/logs/crazyant_service.log
log4j.appender.service.Append=true
log4j.appender.service.MaxFileSize=1GB
log4j.appender.service.MaxBackupIndex=5
log4j.appender.service.layout=org.apache.log4j.PatternLayout
log4j.appender.service.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} [%-5p][%c{1}] [%t] - %m%n
log4j.appender.service.encoding=UTF-8
Copy after login

It can be easily viewed below the configuration file Yes, I output message (message), async (back-end thread), showsql (database log), and service (interface call) to different log files respectively.

Some explanations:

log4j.rootLogger=INFO, console, file

log4j has the concept of a rootLogger and a normal Logger. By default we only need one rootLogger , that is, all logs will only be output to this log file.

Look at the configuration of a common Logger (taking the interface log service as an example):

1. log4j.logger.net.czt.crazyant.service=DEBUG, service

The "net.czt.crazyant.service" in this sentence represents the full path of the package in which the ordinary logger log configuration takes effect.

The "net.czt.crazyant.service" in this sentence represents the name of the ordinary logger.

2.log4j.additivity.net.czt.crazyant.service=false

The "net.czt.crazyant.service" is the same as above, indicating that The package targeted by the configuration item

The meaning of this configuration is not to output the log of the package to the rootLogger log, but only output to the log configured by yourself;

3. log4j.appender.service=org.apache.log4j.RollingFileAppender, and the configuration items under this configuration section

The "service" string here, and the first configuration above The "service" of the item is the same, indicating the configuration of the ordinary Logger;

The configuration items below are the same as the rootLogger, indicating daily output files, encoding UTF8, fragmentation rules, output mode of each line, etc. Wait

The problem I encountered myself was that after configuring the above log4j.properties, I found that each log file was created, but there was no content in it. Why is this? Let’s look at the second point of attention below;

Step 2. When outputting logs, you need to set the specific Class corresponding to the log object

What does it mean? Among the above configuration items, there is a package string of "net.czt.crazyant.service", so let's think about it, how does log4j output the logger logs in different packages to different files? Think about it, there are two types Method:

1. Using interceptor or aop, log4j detects the log output by itself. If it detects which package the log is generated from, it will output it to the corresponding file;

2 , the user passes a Class parameter, log4j obtains the Package corresponding to the Class, and uses this as the standard to locate different log files;

Looking at the code, it is obvious that log4j uses the latter simple method Direct way:

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
  
public class MyClassImpl implements MyClass {
 /**
  * loger
  */
 private static final Log logger = LogFactory.getLog(MyClassImpl.class);
  
 /**
  * my func
  */
 public void myfunc() {
  logger.info("call method myfunc.");
 }
}
Copy after login

In logger = LogFactory.getLog(MyClassImpl.class), the Class parameter using the logger is passed in, and the package address of the Class that is reflected is used by log4j to output The package address of the log.

This approach is also powerful in that it facilitates logical log classification. For example, many codes do not belong to a package, but they logically belong together. For example, message processing is not just about calling the Service through the interface. This package may also call the operation of sending msg. If you want to output some logs in the msg package to the Service, then just pass in a Service Class when the msg logger is initialized.

Or for all logs of a certain type, all their logger objects come from a single encapsulated object instance, and there is only one parameter passed in to this single object instance, which is used to identify this Just classify them logically.

Summary

In Log4j.properties, logs of packages or specific classes are supported to be output separately, but it also needs to be able to correspond to the package in the log configuration when the logger is initialized in the code.

Okay, that’s the entire content of this article. I hope the content of this article can be of some help to everyone’s study or work. If you have any questions, you can leave a message to communicate.

For more related articles on how to use Log4j to output logs of different Packages to different files, 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