使用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 to write into a text file.
我们正在使用java.util.logging.Logger用于生成日志的API。
we are using java.util.logging.Logger API for generating 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屋!
查看全文