Python 3:如何将警告和错误记录到日志文件中?

cbl*_*bll 1 python logging python-3.x

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

它具备三个条件,

While True:

    if something1
        Everything is OK!
    if something2
        Warning
    if something3
        Error
Run Code Online (Sandbox Code Playgroud)

第一,我不想要任何东西。第二,我想向日志文件添加警告。对于第三个,相同 - 除了它是一个错误。

由于这些是在 while 循环中,我是否仍然可以将记录器添加到 something2 和 something3 中?我从下面开始吗?

import logging logger = logging.getLogger()

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

Cha*_*Rai 6

尝试这样做

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')
Run Code Online (Sandbox Code Playgroud)