繁体   English   中英

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

[英]Python 3: How to log warnings and errors to log file?

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

它有三个条件,

While True:

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

首先,我什么都不想要。 第二,我想向日志文件添加警告。 第三,相同-除了是错误。

由于它们处于while循环中,我是否仍可以仅将记录器添加到something2和something3中? 我从下面开始吗?

import logging logger = logging.getLogger()

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

尝试这样做

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

使用日志记录模块:

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所述。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM