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!

JVMmanagesgarbagecollectionacrossplatformseffectivelybyusingagenerationalapproachandadaptingtoOSandhardwaredifferences.ItemploysvariouscollectorslikeSerial,Parallel,CMS,andG1,eachsuitedfordifferentscenarios.Performancecanbetunedwithflagslike-XX:NewRa

Java code can run on different operating systems without modification, because Java's "write once, run everywhere" philosophy is implemented by Java virtual machine (JVM). As the intermediary between the compiled Java bytecode and the operating system, the JVM translates the bytecode into specific machine instructions to ensure that the program can run independently on any platform with JVM installed.

The compilation and execution of Java programs achieve platform independence through bytecode and JVM. 1) Write Java source code and compile it into bytecode. 2) Use JVM to execute bytecode on any platform to ensure the code runs across platforms.

Java performance is closely related to hardware architecture, and understanding this relationship can significantly improve programming capabilities. 1) The JVM converts Java bytecode into machine instructions through JIT compilation, which is affected by the CPU architecture. 2) Memory management and garbage collection are affected by RAM and memory bus speed. 3) Cache and branch prediction optimize Java code execution. 4) Multi-threading and parallel processing improve performance on multi-core systems.

Using native libraries will destroy Java's platform independence, because these libraries need to be compiled separately for each operating system. 1) The native library interacts with Java through JNI, providing functions that cannot be directly implemented by Java. 2) Using native libraries increases project complexity and requires managing library files for different platforms. 3) Although native libraries can improve performance, they should be used with caution and conducted cross-platform testing.

JVM handles operating system API differences through JavaNativeInterface (JNI) and Java standard library: 1. JNI allows Java code to call local code and directly interact with the operating system API. 2. The Java standard library provides a unified API, which is internally mapped to different operating system APIs to ensure that the code runs across platforms.

modularitydoesnotdirectlyaffectJava'splatformindependence.Java'splatformindependenceismaintainedbytheJVM,butmodularityinfluencesapplicationstructureandmanagement,indirectlyimpactingplatformindependence.1)Deploymentanddistributionbecomemoreefficientwi

BytecodeinJavaistheintermediaterepresentationthatenablesplatformindependence.1)Javacodeiscompiledintobytecodestoredin.classfiles.2)TheJVMinterpretsorcompilesthisbytecodeintomachinecodeatruntime,allowingthesamebytecodetorunonanydevicewithaJVM,thusfulf


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SublimeText3 Chinese version
Chinese version, very easy to use

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.
