log4j输出日志到不同文件

时间:2021-06-17 19:53:23
1.先看log4j的配置文件 log4j.properties 没有此文件就在根目录下创建一个:
log4j.rootLogger=INFO,R,Client
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=./log/server.log
log4j.appender.R.MaxFileSize=5MB
log4j.appender.R.MaxBackupIndex=10
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=[%5p] %d [%X{userName}] [%X{remoteIp}] %m%n
log4j.logger.Client=INFO,Client
log4j.additivity.Client = false
log4j.appender.Client=org.apache.log4j.RollingFileAppender
log4j.appender.Client.File=./log/client.log
log4j.appender.Client.MaxFileSize=5MB
log4j.appender.Client.MaxBackupIndex=10
log4j.appender.Client.layout=org.apache.log4j.PatternLayout
log4j.appender.Client.layout.ConversionPattern=[%5p] %d [%X{userName}] [%X{remoteIp}] %m%n
此日志文件分为两个日志文件.一个是给服务器程序记录日志,另一个是给客户端程序记录日志的.
红色部分是必须要加的.
log4j.additivity.Client = false 确保写入client.log文件信息不重复出现到server.log文件中.
log4j.logger.Client=INFO,Client 确保只对log4j的info信息感兴趣. 2.再看代码的初使化:
//加入log4j支持
static Logger logger =Logger.getLogger("Client");
public class test {
static Logger logger =Logger.getLogger("Client");
public static void main(String[] args){
logger.info("333333333");
}
}