python:将所有错误记录到单个日志文件中

时间:2018-07-18 12:19:46

标签: python error-handling error-logging

我正在用python编写工具,我想将所有错误-仅将错误-(无法通过的计算)放入单个日志文件中。另外,我想在代码的每个部分的错误日志文件中使用不同的文本,以使错误日志文件易于理解。我该如何编码?非常感谢谁可以提供帮助!

1 个答案:

答案 0 :(得分:0)

检出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文档),但这是我每次登录项目时的起点。我发现将配置保存在专用的配置文件中很有帮助,而不是通过定义登录代码来污染项目。