Home  >  Article  >  Java  >  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

高洛峰
高洛峰Original
2017-01-18 12:42:241253browse

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

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.");
 }
}

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