使用 java.util.logging.Logger 时如何在文本文件中写入日志 [英] How to write logs in text file when using java.util.logging.Logger
本文介绍了使用 java.util.logging.Logger 时如何在文本文件中写入日志的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一种情况,我想将我创建的所有日志写入一个文本文件.
I have a situation in which I want to write all logs created by me into a text file.
我们使用 java.util.logging.Logger API 来生成日志.
We are using java.util.logging.Logger API to generate the logs.
我试过了:
private static Logger logger = Logger.getLogger(className.class.getName());
FileHandler fh;
fh = new FileHandler("C:/className.log");
logger.addHandler(fh);
但仍然只在控制台上获取我的日志....
But still getting my logs on console only....
推荐答案
试试这个示例.它对我有用.
Try this sample. It works for me.
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?");
}
在 MyLogFile.log 中生成输出
Produces the output at MyLogFile.log
Apr 2, 2013 9:57:08 AM testing.MyLogger main
INFO: My first log
Apr 2, 2013 9:57:08 AM testing.MyLogger main
INFO: Hi How r u?
要删除控制台处理程序,请使用
To remove the console handler, use
logger.setUseParentHandlers(false);
因为 ConsoleHandler 已注册到所有记录器派生自的父记录器.
since the ConsoleHandler is registered with the parent logger from which all the loggers derive.
这篇关于使用 java.util.logging.Logger 时如何在文本文件中写入日志的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文