我想使用 Log4j API,但在配置上遇到了一点问题。
这是我的 LogWriter 类:
public class LogWriter {
static Logger logger = Logger.getLogger(LogWriter.class);
public LogWriter(String logFilePath) {
File outFile = new File(logFilePath);
try {
PrintStream outStream = new PrintStream(new FileOutputStream(outFile));
System.setOut(outStream));
System.setErr(outStream);
} catch (FileNotFoundException e) {
throw new IllegalArgumentException("File not Found");
}
BasicConfigurator.configure();
}
public void write(String infoString) {
logger.info(infoString);
}
}
现在这工作正常,但我不能同时写入 Logger-File 和控制台(可能是因为System.setOut
)
我添加了一个如下所示的 log4j.properties 文件:
# Root logger option
log4j.rootLogger=INFO, console
# Direct log messages to console
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.Target=System.out
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%-5p- %m%n
现在我的问题是,我怎样才能让我的 LogWriter 和 log4j.properties 文件一起工作,以便输出进入 Logger-File 和控制台?我必须在我的 LogWriter 中进行哪些更改?