【问题标题】:Python 3: How to log warnings and errors to log file?Python 3:如何将警告和错误记录到日志文件?
【发布时间】:2017-06-05 11:36:07
【问题描述】:

假设我有一个永远运行的While 循环(它进行系统监控)。

它有三个条件,

While True:

    if something1
        Everything is OK!
    if something2
        Warning
    if something3
        Error

第一个,我什么都不想要。第二,我想在日志文件中添加警告。对于第三个,相同 - 除了它是一个错误。

由于这些都在一个while循环中,我仍然可以在something2和something3中添加一个记录器吗?我应该从以下开始吗?

import logging logger = logging.getLogger()

但是如何为每个 if 语句添加警告和错误,以便写入同一个日志文件?

【问题讨论】:

标签: python python-3.x logging


【解决方案1】:

使用logging模块:

import logging
logging.basicConfig(filename='logfile.log', level=logging.DEBUG, 
                    format='%(asctime)s %(levelname)s %(name)s %(message)s')
logger=logging.getLogger(__name__)
...    

try:
    1/0
except ZeroDivisionError as err:
    logger.error(err)
...

你也可以写logging.warninglogging.info,正如@crai 所说。

【讨论】:

    【解决方案2】:

    尝试这样做

    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')
    

    【讨论】:

    • 不打印警告或错误的信息(文件、行和错误/警告本身)。在这些情况下使用:logging.captureWarnings(True) ... 来捕获警告很重要。
    猜你喜欢
    • 2011-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-26
    • 1970-01-01
    • 2020-09-14
    相关资源
    最近更新 更多