【发布时间】:2019-08-12 14:05:39
【问题描述】:
我正在重写一个从 bash 到 Python-3.x 的小型守护程序,以拥有更强大的语言。我对 Python 语言真的很陌生。
所以,我正在尝试使用 Python 的日志记录模块在我的脚本中记录消息。我想通过Syslog 使用SysLogHandler 记录除调试级别以外的所有消息级别,并在仅启用--debug 选项的情况下将调试消息记录到文件中。
我在 Gentoo Gnu/linux 上使用 Python-3.6。这是为 gentoo 的 portage 包管理器自动同步和自动伪装世界更新的守护进程。
我已经使用SysLogHandler 设置了通过Syslog 的日志记录,并且显示了所有期望用于调试的消息。
我还使用WatchedFileHandler 设置了通过文件的日志记录,但我还没有找到只过滤调试消息的方法。
仅当启用--debug 选项时,我都没有找到启用调试的方法。
我的代码:
import logging, logging.handlers
debug_log = "debug.log"
debug = "no"
def Create_logger():
"""Setup the logging environment"""
logging.addLevelName(logging.CRITICAL, '[Crit ]')
logging.addLevelName(logging.ERROR, '[Error]')
logging.addLevelName(logging.WARNING, '[Warn ]')
logging.addLevelName(logging.INFO, '[Info ]')
logging.addLevelName(logging.DEBUG, '[Debug]')
logger = logging.getLogger(name)
# Debug part
file_handler = logging.handlers.WatchedFileHandler(debug_log)
file_handler.setLevel(logging.DEBUG)
file_formatter = logging.Formatter('%(asctime)s %(name)s %(levelname)s %(message)s')
file_handler.setFormatter(file_formatter)
logger.addHandler(file_handler)
# Syslog part
syslog_handler = logging.handlers.SysLogHandler(address='/dev/log',facility='daemon')
syslog_handler.setLevel(logging.INFO)
syslog_formatter = logging.Formatter('%(name)s %(levelname)s %(message)s')
syslog_handler.setFormatter(syslog_formatter)
logger.addHandler(syslog_handler)
return logger
log=Create_logger()
log.error('This is error')
log.setLevel(logging.CRITICAL)
log.error('This is an second error')
log.critical('This is critical !!!')
log.setLevel(logging.INFO)
log.info('Hello world :p')
log.debug('this is an debug message')
log.setLevel(logging.DEBUG)
log.debug(f'This is an other debug message and debug log is locate to {debug_log}')
我从/var/log/messages(系统日志)得到的信息:
Aug 9 23:43:23 Gentoo syuppod[26195]: [Error] This is error
Aug 9 23:43:23 Gentoo syuppod[26195]: [Crit ] This is critical !!!
Aug 9 23:43:23 Gentoo syuppod[26195]: [Info ] Hello world :p
我从 debug.log 中得到的信息:
2019-08-09 23:43:23,052 syuppod [Error] This is error
2019-08-09 23:43:23,052 syuppod [Crit ] This is critical !!!
2019-08-09 23:43:23,052 syuppod [Info ] Hello world :p
2019-08-09 23:43:23,052 syuppod [Debug] This is an other debug message and debug log is locate to debug.log
所以,Syslog 日志记录可以,但debug.log 文件不行,我在函数Create_logger() 中声明所有调试部分之前尝试了if debug == "yes" 语句,但它不起作用。
我还找到了this question,但它的答案只涵盖了我正在尝试做的一半。我仍在尝试在可用文档中找到解决方案。
你能告诉我吗?
【问题讨论】:
标签: python-3.x logging