Java Logger 仅用于文件,无屏幕输出
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/920654/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java Logger only to file, no screen output
提问by Jaran
I have quite a simple problem but can't find a solution for it. I have a logger with a file handler added, but it still spams the hell out of my console. How could I get the logger to solely route all output to a file, with NO console outputs?
我有一个很简单的问题,但找不到解决方案。我有一个添加了文件处理程序的记录器,但它仍然在我的控制台中发送垃圾邮件。我怎样才能让记录器将所有输出单独路由到一个文件,而没有控制台输出?
采纳答案by Bombe
Remove all handlers (using Logger.getHandlers()and calling Logger.removeHandler()for each handler) from the root logger before adding your file handler.
在添加文件处理程序之前,从根记录器中删除所有处理程序(使用Logger.getHandlers()并为每个处理程序调用Logger.removeHandler())。
回答by Jaran
Old question but to help other developers:
老问题,但要帮助其他开发人员:
You can also just use logger.setUseParentHandlers(false)on your logger.
您也可以只logger.setUseParentHandlers(false)在记录器上使用。
回答by Lachlan
The simplest way to guarantee that nothing will be written to the console is to put:
保证不会向控制台写入任何内容的最简单方法是:
java.util.logging.ConsoleHandler.level = NONE
in your logging configuration file.
在您的日志记录配置文件中。
回答by Bob Yoplait
Use log4j with
使用 log4j
import org.apache.log4j.Logger;
Logger logger = Logger.getLogger("com.whatever");
PropertyConfigurator.configure("file-log4j.properties");
and set your display levels in file-log4j.properties:
并在 file-log4j.properties 中设置您的显示级别:
# Root logger option
log4j.rootLogger=INFO, file
# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=index-service.log
log4j.appender.file.MaxFileSize=1MB
log4j.appender.file.MaxBackupIndex=1
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
log4j.appender.file.Append=false
回答by Nguy?n Anh Qu?
I use:
我用:
Logger logger = Logger.getLogger("MyLog");
Logger parentLog= logger.getParent();
if (parentLog!=null&&parentLog.getHandlers().length>0) parentLog.removeHandler(parentLog.getHandlers()[0]);

