【问题标题】:python: logging all errors into single log filepython:将所有错误记录到单个日志文件中
【发布时间】:2018-12-26 08:46:15
【问题描述】:

我正在用 python 编写一个工具,我想把所有错误——而且只有错误——(没有按应有的计算)放到一个日志文件中。此外,我希望在我的代码的每个部分的错误日志文件中都有不同的文本,以使错误日志文件易于解释。我该如何编码?非常感谢谁能提供帮助!

【问题讨论】:

    标签: python error-handling error-logging


    【解决方案1】:

    查看python模块logging。这是一个核心模块,不仅可以在您自己的项目中统一日志记录,还可以在第三方模块中统一记录。

    对于最小的日志文件示例,这直接取自the documentation

    import logging
    logging.basicConfig(filename='example.log',level=logging.DEBUG)
    logging.debug('This message should go to the log file')
    logging.info('So should this')
    logging.warning('And this, too')
    

    这导致example.log的内容:

    DEBUG:root:This message should go to the log file
    INFO:root:So should this
    WARNING:root:And this, too
    

    不过,我个人推荐使用yaml配置方式(需要pyyaml):

    #logging_config.yml
    
    version: 1
    disable_existing_loggers: False
    formatters:
      standard:
        format: '%(asctime)s [%(levelname)s] %(name)s - %(message)s'
    handlers:
      console:
        class: logging.StreamHandler
        level: INFO
        formatter: standard
        stream: ext://sys.stdout
      file:
        class: logging.FileHandler
        level: DEBUG
        formatter: standard
        filename: output.log
      email:
        class: logging.handlers.SMTPHandler
        level: WARNING
        mailhost: smtp.gmail.com
        fromaddr: to@address.co.uk
        toaddrs: to@address.co.uk
        subject: Oh no, something's gone wrong!
        credentials: [email, password]
        secure: []
    root:
      level: DEBUG
      handlers: [console, file, email]
      propagate: True
    

    然后使用,例如:

    import logging.config
    import yaml
    
    with open('logging_config.yml', 'r') as config:
        logging.config.dictConfig(yaml.safe_load(config))
    
    logger = logging.getLogger(__name__)
    
    logger.info("This will go to the console and the file")
    logger.debug("This will only go to the file")
    logger.error("This will go everywhere")
    
    try:
        list = [1, 2, 3]
        print(list[10])
    except IndexError:
        logger.exception("This will also go everywhere")
    

    打印出来:

    2018-07-18 13:29:21,434 [INFO] __main__ - This will go to the console and the file
    2018-07-18 13:29:21,434 [ERROR] __main__ - This will go everywhere
    2018-07-18 13:29:21,434 [ERROR] __main__ - This will also go everywhere
    Traceback (most recent call last):
      File "C:/Users/Chris/Desktop/python_scratchpad/a.py", line 16, in <module>
        print(list[10])
    IndexError: list index out of range
    

    虽然日志文件的内容是:

    2018-07-18 13:35:55,423 [INFO] __main__ - This will go to the console and the file
    2018-07-18 13:35:55,424 [DEBUG] __main__ - This will only go to the file
    2018-07-18 13:35:55,424 [ERROR] __main__ - This will go everywhere
    2018-07-18 13:35:55,424 [ERROR] __main__ - This will also go everywhere
    Traceback (most recent call last):
      File "C:/Users/Chris/Desktop/python_scratchpad/a.py", line 15, in <module>
        print(list[10])
    IndexError: list index out of range
    

    当然,您可以添加或删除处理程序、格式化程序等,或在代码中执行所有这些操作(请参阅 Python 文档),但这是我在项目中使用日志记录时的起点。我发现在专用配置文件中进行配置而不是通过在代码中定义日志来污染我的项目是很有帮助的。

    【讨论】:

      猜你喜欢
      • 2020-09-14
      • 1970-01-01
      • 2011-07-25
      • 2023-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-05
      • 2018-07-19
      相关资源
      最近更新 更多