如何在java中打印文件中的所有日志信息
从其他来源,我读到了一种使用记录器的方法如何在java中打印文件中的所有日志信息,java,logging,output,java.util.logging,Java,Logging,Output,Java.util.logging,从其他来源,我读到了一种使用记录器的方法 public static void main(String[] args) { Logger logger = Logger.getLogger("MyLog"); FileHandler fh; try { // This block configure the logger with handler and formatter fh = new F
public static void main(String[] args) {
Logger logger = Logger.getLogger("MyLog");
FileHandler fh;
try {
// This block configure the logger with handler and formatter
fh = new FileHandler("C:/temp/test/MyLogFile.log");
logger.addHandler(fh);
SimpleFormatter formatter = new SimpleFormatter();
fh.setFormatter(formatter);
// the following statement is used to log any messages
logger.info("My first log");
} catch (SecurityException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
logger.info("Hi How r u?");
}
在上面的示例中,记录器信息由我们输入。但是如何将程序返回的所有现有警告信息打印到输出文本文件中。我能够将程序中给出的控制台输出打印到文件中,同时在控制台中打印其他警告信息和日志。还有其他方法吗?不要使用语句e.printStackTrace(),让我们在catch块中尝试类似于logger.log(Level.ALL,e.getMessage(),e)的语句 比如说,
import java.util.logging.Level;
import java.util.logging.Logger;
...
catch (SecurityException e) {
logger.log(Level.ALL, e.getMessage(), e);
}
catch (IOException e) {
logger.log(Level.ALL, e.getMessage(), e);
}
您也可以尝试Log4J问题是其他代码很可能使用不同的记录器。使用java.util.logging,您可以在应用程序启动时正确配置根记录器,其他记录器将继承该配置
private static void configureRootLogger() {
try {
FileHandler fh = new FileHandler("MyLogFile.log");
fh.setFormatter(new SimpleFormatter());
Logger.getLogger("").addHandler(fh);
} catch (IOException e) {
// handle exception
}
}
完整示例:
import java.io.IOException;
import java.util.logging.FileHandler;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
public class LogToFileExample {
private static final Logger logger = Logger.getLogger("MyLogA");
public static void main(String[] args) {
configureRootLogger();
logger.info("local test message");
final LogTester tester = new LogTester();
tester.logMessage();
}
private static void configureRootLogger() {
try {
FileHandler fh = new FileHandler("MyLogFile.log");
fh.setFormatter(new SimpleFormatter());
Logger.getLogger("").addHandler(fh);
} catch (IOException e) {
logger.warning("Could not add handler to log to file");
}
}
}
文件和控制台中的相同输出:
May 28, 2021 9:44:50 AM org.testing.LogToFileExample main
INFO: local test message
May 28, 2021 9:44:50 AM org.testing.LogTester logMessage
INFO: external log message
看见
May 28, 2021 9:44:50 AM org.testing.LogToFileExample main
INFO: local test message
May 28, 2021 9:44:50 AM org.testing.LogTester logMessage
INFO: external log message