我正在使用log4j2将消息记录到控制台和一个文本文件。我可以将内容记录到控制台,但无法写入文本文件(文本文件为空) 这是代码
package de.code.logwizard;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.config.Configurator;
public class Log4JarLogger
{
public static Logger getLogger(Class<?> clazz)
{
return LogManager.getLogger(clazz);
}
public static void configure()
{
final String propertyFileName = System.getProperty("user.dir") + LOG4J_FILE;
System.out.println(propertyFileName);
Configurator.initialize(null, propertyFileName);
LogManager.getLogger(Log4JarLogger.class).info("Logging initialized from file '" + propertyFileName + "'.");
}
private static final String LOG4J_FILE = "\\log4j2Test.properties";
}
-
import de.code.logwizard.Log4JarLogger;
public class TestLogger
{
public static void main(String[] args)
{
Log4JarLogger.configure();
_logger = Log4JarLogger.getLogger(TestLogger.class);
_logger.debug("This is DEBUG");
_logger.info("This is INFO");
_logger.warn("This is WARN");
_logger.error("This is ERROR");
_logger.fatal("This is FATAL");
}
private static org.apache.logging.log4j.Logger _logger;
}
和属性文件:
property.filename = logs
appenders = console, file
appender.console.type = Console
appender.console.name = STDOUT
appender.console.layout.type = PatternLayout
appender.console.layout.pattern = [%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n
appender.file.type = File
appender.file.name = LOGFILE
appender.file.fileName = target/rolling/rollingtest.log
appender.file.layout.type = PatternLayout
appender.file.layout.pattern = [%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n
loggers = file
logger.file.name = com.testcase
logger.file.level = debug
logger.file.appenderRefs = file
logger.file.appenderRef.file.ref = LOGFILE
rootLogger.level = debug
rootLogger.appenderRefs = stdout
rootLogger.appenderRef.stdout.ref = STDOUT
我猜想这行Configurator.initialize(null,propertyFileName);是无法解决的原因?
答案 0 :(得分:1)
log4j记录器配置是问题。如果您想同时在控制台和控制台上登录文件,请尝试更改记录器配置,例如-
loggers = file
# mention your root package name of the project in below key
logger.file.name = de.code.logwizard
logger.file.level = debug
logger.file.additivity = debug
logger.file.appenderRef.file.ref = LOGFILE
logger.file.appenderRef.console.ref = STDOUT
rootLogger.level = debug
rootLogger.additivity = false
rootLogger.appenderRef.rolling.ref = LOGFILE
rootLogger.appenderRef.console.ref = STDOUT
来到配置文件中的问题-
logger.file.name
的值应该是项目的根包名称。但是,在您的配置文件中,它是com.testcase
追加程序引用声明中的语法错误。应该是appenderRef
而不是appenderRefs