How to create multiple log files of different content with log4j

天涯浪子 提交于 2019-12-11 17:37:27

问题


I'm tried to create multiple log files of different content with log4j.
This is my log4j.properties file

# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=/home/dhanushka/Documents/log4j.log
log4j.appender.file.MaxFileSize=1MB
log4j.appender.file.MaxBackupIndex=1
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %-5p [%c{1}] %m%n

log4j.appender.testng=org.apache.log4j.RollingFileAppender
log4j.appender.testng.File=/home/dhanushka/Documents/TestNGlog.log
log4j.appender.testng.MaxFileSize=1MB
log4j.appender.testng.MaxBackupIndex=1
log4j.appender.testng.layout=org.apache.log4j.PatternLayout
log4j.appender.testng.layout.ConversionPattern=%d{ABSOLUTE} %-5p [%c{1}] %m%n

# Direct log messages to stdout
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}] %m%n

# Root logger option
log4j.rootLogger=INFO, file, admin, stdout, testng


# Log everything. Good for troubleshooting
log4j.logger.org.hibernate=INFO

# Log all JDBC parameters
log4j.logger.org.hibernate.type=ALL


Here is how I implemented in code.

public class VerifyAmenities {

private static Logger defaultLogger = Logger.getLogger("file");
private static Logger testNGlogger = Logger.getLogger("testng");
.
.
}
defaultLogger.info("This is default Logger");
testNGlogger.info("This is testNG Logger");

By this it creates two log files. But Both has same logs. Appreciate any ones reply.


回答1:


Finally I found the way of doing this.

# Root logger option
log4j.rootLogger=TRACE, stdout, file

log4j.category.testngLogger=DEBUG, testng
log4j.additivity.testngLogger=false

In rootLogger, that is like a father of all logs. It inherit by default. Root logger option should be like that.
If you additivity set to false it will never goes to rootLogger

In log4j.xml file it will goes like this.

<logger name="testngLogger" additivity="false">
    <level value="DEBUG" />
    <appender-ref ref="testngLogger" />
</logger>

<root>
    <priority value="INFO" />
    <appender-ref ref="CONSOLE" />
    <appender-ref ref="fileLogger" />
</root>


来源:https://stackoverflow.com/questions/47285254/how-to-create-multiple-log-files-of-different-content-with-log4j

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!