簡體   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