簡體   English   中英

Python:向控制台和日志文件顯示和記錄運行時錯誤

[英]Python: Display and log runtime errors to console and log file

下面的腳本是將所有錯誤寫入日志文件和控制台,除了引發的異常,它只寫在控制台而不是日志上。 如何讓它將引發的異常寫入日志,或任何運行時異常? 謝謝。

import os
import sys
import logging
import logging.config

class Main(object):

    @staticmethod
    def main():
    logging.config.fileConfig("logging.conf")
    logging.debug("1")
    logging.info("2")
    logging.warn("3")
    logging.error("4")
    logging.critical("5")
    raise Exception("test")

if __name__ == "__main__":
    Main.main()


import logging
import logging.config

logging.config.fileConfig('logging.conf')

# create logger
logger = logging.getLogger('simpleExample')

# 'application' code
logger.debug('debug message')
logger.info('info message')
logger.warn('warn message')
logger.error('error message')
logger.critical('critical message')
raise Exception("Exception raised")

配置文件:

[loggers]
keys=root,simpleExample

[handlers]
keys=consoleHandler

[formatters]
keys=simpleFormatter

[logger_root]
level=DEBUG
handlers=consoleHandler

[logger_simpleExample]
level=DEBUG
handlers=consoleHandler
qualname=simpleExample
propagate=0

[handler_fileHandler]
formatter=simpleFormatter
args=('error.log')

[handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=simpleFormatter
args=(sys.stdout,)

[formatter_simpleFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
datefmt=

為了使用logging模塊捕獲所有錯誤,第一個要求是使用except語句捕獲所有錯誤。 一旦捕獲它們,就必須根據錯誤級別調用Logger.exception()或其他合適的函數。

如果您事先無法捕獲所有異常,最好的辦法是將stdoutstderr重定向到文件。 然后,執行tail -f來模擬控制台輸出。 無論如何,一個未捕獲的異常將導致您的程序執行被停止。

但是,我寧願嘗試捕捉所有異常,即使這意味着必須做這樣的事情。

try:
    Main.main()
except Exception as e:
    logging.Exception("Unexpected exception! %s",e)

這允許您使用整潔的logging模塊,而不必依賴於糟糕的輸出重定向。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM