我想根据变量将 log4j 日志写入标准输出或文件。如果设置了变量 writeLogToFile,则日志应写入文件,否则写入标准输出。
我已尝试使用以下代码,但日志被写入文件和标准输出。
public class LTE {
private static Logger logger = Logger.getLogger(LTE.class);
public static void main(String[] args) {
/*some code which sets variables writeLogToFile and logFile*/
BasicConfigurator.configure();
if(writeLogToFile) {
FileAppender fappender = new FileAppender(new PatternLayout("%-6p [%t] (%F:%L) %m%n"), logFile);
logger.addAppender(fappender);
}
/*some code which uses info and debug methods to write log*/
}
}
这在我希望将日志写入标准输出时有效,因为默认情况下日志会写入标准输出。但是当我想将日志写入文件时,这会失败。日志既写入标准输出,也写入文件。
所以,我尝试了以下代码,但这也不起作用。
public class LTE {
private static Logger logger = Logger.getLogger(LTE.class);
public static void main(String[] args) {
/*some code which sets variables writeLogToFile and logFile*/
BasicConfigurator.configure();
if(writeLogToFile) {
FileAppender fappender = new FileAppender(new PatternLayout("%-6p [%t] (%F:%L) %m%n"), logFile);
logger.addAppender(fappender);
Properties logProperties = new Properties();
logProperties.setProperty("log4j.additivity.notRootLogger", "false");
PropertyConfigurator.configure(logProperties);
}
/*some code which uses info and debug methods to write log*/
}
}
我也尝试了以下
public class LTE {
private static Logger logger = Logger.getLogger(LTE.class);
public static void main(String[] args) {
/*some code which sets variables writeLogToFile and logFile*/
BasicConfigurator.configure();
if(writeLogToFile) {
FileAppender fappender = new FileAppender(new PatternLayout("%-6p [%t] (%F:%L) %m%n"), logFile);
logger.addAppender(fappender);
}
else {
ConsoleAppender cappender = new ConsoleAppender(new PatternLayout("%-6p [%t] (%F:%L) %m%n"), "System.out");
logger.addAppender(cappender);
}
/*some code which uses info and debug methods to write log*/
}
}
有人可以帮我解决这个问题吗?
[编辑]
好的。我想我解决了这个问题。logger.setAdditivity(false);
我在我的代码中添加了这样一行
public class LTE {
private static Logger logger = Logger.getLogger(LTE.class);
public static void main(String[] args) {
/*some code which sets variables writeLogToFile and logFile*/
BasicConfigurator.configure();
if(writeLogToFile) {
FileAppender fappender = new FileAppender(new PatternLayout("%-6p [%t] (%F:%L) %m%n"), logFile);
logger.addAppender(fappender);
logger.setAdditivity(false); //added line here
}
/*some code which uses info and debug methods to write log*/
}
}
现在它工作正常。如果writeLogToFile=true
然后将日志写入标准输出,否则将其写入文件。