Python 日志记录:禁用输出到标准输出 [英] Python logging: disable output to stdout
本文介绍了Python 日志记录:禁用输出到标准输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图让程序只使用 SysLogHandler 实例进行日志记录,而不使用其他处理程序.我希望它不会登录到任何文件或标准输出.
I'm trying to make a program use only the SysLogHandler instance for logging and no other handlers. I expect it to not log to any files or stdout.
self.logger = logging.getLogger(self.name)
syslog_handler = logging.handlers.SysLogHandler(
socktype=socket.AF_UNIX,
address='/dev/log',
facility=logging.handlers.SysLogHandler.LOG_LOCAL4,
)
# Check if there is a handler attached
if len(self.logger.handlers) > 0:
# If there is a handler attached
# ensure it is a SysLogHandler instance
handler = self.logger.handlers[0]
if not (handler.__class__ == logging.handlers.SysLogHandler):
# If is was something else but a SysLogHandler instance,
# remove it and attach the syslog_handler
self.logger.handlers = []
self.logger.addHandler(syslog_handler)
else:
# If no handlers attached,
# attach syslog_handler
self.logger.handlers = []
self.logger.addHandler(syslog_handler)
但是使用此设置,当使用 python srcipt.py
But with this setup it continues to spit lines out to stdout when run with python srcipt.py
推荐答案
你有不同的方法来做到这一点:
You have different ways to do so:
-将 logger.propagate 设置为 false.
-set logger.propagate to false.
您可以创建游览自己的流,如下所示:
you can create tour own stream, like this:
https://docs.python.org/2/library/io.html#io.StringIO
并将其交给您的记录器.
And give it to your logger.
logging.StreamHandler(stream=None)
这篇关于Python 日志记录:禁用输出到标准输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文