【问题标题】:How to log only debug messages to a file using Python's logging module and enable debug mode as an option?如何使用 Python 的日志记录模块仅将调试消息记录到文件并启用调试模式作为选项?
【发布时间】: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


    【解决方案1】:

    好的,我在阅读了可用的文档后找到了它:https://stackoverflow.com/a/7447596/190597 (robert) Thx !!

    这是我的工作代码:

    #!/usr/bin/env python3
    # -*- coding: utf-8 -*-
    # -*- python -*- 
    
    
    import sys, os, argparse
    import logging, logging.handlers
    
    __version__ = "0.1-beta1"
    name = os.path.basename(os.path.splitext(sys.argv[0])[0])
    name_with_ext = os.path.basename(sys.argv[0])
    basedir = "/var/lib/" + name
    logdir = "/var/log/" + name
    
    # This is for testing only, should go to /var/log/'name'
    debug_log = "debug.log"
    
    class LogLevelFilter(logging.Filter):
        """https://stackoverflow.com/a/7447596/190597 (robert)"""
        def __init__(self, level):
            self.level = level
    
        def filter(self, record):
            # Just revert >= to <= then get only current level or lower.
            return record.levelno <= self.level
    
    
    def CreateLogger():
        """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)
    
        # File debug only part
        file_handler     = logging.handlers.WatchedFileHandler(debug_log)   
        file_formatter   = logging.Formatter('%(asctime)s  %(name)s  %(levelname)s  %(message)s')
        file_handler.setFormatter(file_formatter)
        file_handler.addFilter(LogLevelFilter(logging.DEBUG))
        file_handler.setLevel(logging.DEBUG)
        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
    
    
    parser = argparse.ArgumentParser(description='Daemon which automate git update and sync, pretend world update for gentoo portage package manager.',
                                     epilog='Without opts, %(prog)s will start in log level \'info\'')
    
    parser.add_argument('-d', '--debug', help='Start daemon in log level \'debugg\'', action="store_true")
    parser.add_argument('-q', '--quiet', help='Start daemon in log level \'quiet\'', action="store_true")
    parser.add_argument('-v', '--version', action='version', version='%(prog)s: ' + __version__ + ' - Copyright (C) 2019 Jérôme Venturi, <jerome dot venturi at gmail dot com> - License: GNU/GPL V3.')
    args = parser.parse_args()
    
    log=CreateLogger()
    # Edited : add log level info or it won't display 'log.info('Hello, how are you?') in /var/log/messages (syslog)
    log.setLevel(logging.INFO)
    # For Testing
    log.debug('This is a debug messages but you should\'nt see it !')
    log.info('Hello, how are you ?')
    log.error('This is an error !')
    log.critical('This is an critial msg and i should exit after this !')
    
    if args.debug:
        log.setLevel(logging.DEBUG)
        log.info(f'Debug log has been enable in {debug_log}')
        log.debug('Debug has been enable.')
    
    
    log.debug(f'This is an other debug message and debug log is locate to {debug_log}')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-01
      • 2020-11-07
      • 2014-02-28
      • 1970-01-01
      • 2014-11-02
      • 1970-01-01
      相关资源
      最近更新 更多