Log4j未保存到文件中

时间:2018-08-08 07:21:06

标签: java log4j

我尝试使用log4j将错误日志保存到文件中。我的代码如下:

导入:

import org.apache.log4j.Logger;

代码:

private Logger logger2 = Logger.getLogger(ExceptionSaver.class);
logger2.info("Logger is configured correctly but sth is wrong " + e.getMessage());

配置文件log4j.properties

log4j.rootLogger=DEBUG, default.out, default.file

# System.out.println appender for all classes
log4j.appender.default.out=org.apache.log4j.ConsoleAppender
log4j.appender.default.out.threshold=DEBUG
log4j.appender.default.out.layout=org.apache.log4j.PatternLayout
log4j.appender.default.out.layout.ConversionPattern=%-5p %c: %m%n

log4j.appender.default.file=org.apache.log4j.FileAppender
log4j.appender.default.file.append=true
log4j.appender.default.file.file=/logs/mylogfile.log
log4j.appender.default.file.threshold=INFO
log4j.appender.default.file.layout=org.apache.log4j.PatternLayout
log4j.appender.default.file.layout.ConversionPattern=%-5p %c: %m%n

我的代码在里面: main / java / com / co / sp / el / cl / log

Config位于内部: 主要/资源

不幸的是,日志仅在控制台内打印。没有使用日志创建文件。项目是用gradle构建的,我添加了依赖性

compile group: 'log4j', name: 'log4j', version: '1.2.17'

1 个答案:

答案 0 :(得分:0)

我解决了,我将配置更改为:

log4j.rootLogger=debug, stdout, R

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

# Pattern to output the caller's file name and line number.
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n

log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=./logs/logError.log

log4j.appender.R.MaxFileSize=100KB
# Keep one backup file
log4j.appender.R.MaxBackupIndex=1

log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n