我有一个log4j2.xml文件,用于定义一些输出到.log文件的记录器。
<?xml version="1.0" encoding="UTF-8" ?> <Configuration> <Appenders> <Console name="ConsoleAppender" target="SYSTEM_OUT"> <PatternLayout pattern="%d{MM-dd HH:mm:ss } %p - %m%n"/> </Console> <File name="LogFileAppender" fileName="${sys:logFileName}" append="false"> <PatternLayout> <Pattern>%d [%t] %p - %m%n</Pattern> </PatternLayout> </File> </Appenders> <Loggers> <Root level="error"> <AppenderRef ref="ConsoleAppender" /> <AppenderRef ref="LogFileAppender"/> </Root> </Loggers> </Configuration>
在fileNames已被读取之后,我在java中为记录器.xml设置了完整的路径。
public static void initializeLoggers(String logPath) // set output paths for log files System.setProperty("logFileName", logPath + "PROJECT.log"); // reconfigure loggers with paths org.apache.logging.log4j.core.LoggerContext ctx = (org.apache.logging.log4j.core.LoggerContext) LogManager.getContext(false);