我想根據變量將log4j日誌寫入標準輸出或文件。如果設置了變量writeLogToFile,則日誌應該寫入文件,否則寫入標準輸出。將日誌寫入標準輸出或log4j中的文件java
我已經嘗試使用下面的代碼,但日誌被寫入文件以及標準輸出。
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*/
}
}
當我希望日誌寫入標準輸出時,默認情況下會將日誌寫入標準ouptput。但是,當我想將日誌寫入文件時,這會失敗。日誌既寫入標準輸出也寫入文件。
所以,我試了下面的代碼,但這也沒有奏效。
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
則日誌寫入標準輸出,否則寫入文件。
粘貼你的log4j配置文件 – Drona
我在保羅答覆的答覆中粘貼了配置文件。順便說一句,我找到了解決方案,並且我已經相應地編輯了我原來的帖子。 – jyotesh