標籤:

Python通用日誌類

寫程序,離不開記錄程序運行的日誌,python記錄日誌。提供了很多方式,下面學習一下如何利用logging模塊記錄日誌。

# -*- coding:UTF-8 -*-通用日誌類作者:天堂的鴿子時間:2017-2-26import loggingimport logging.configclass Logger: 日誌類 def __init__(self, filename=logger.log): logging.basicConfig( level=logging.DEBUG, format=%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s, datefmt=%Y-%m-%d %H:%M:%S, filename=filename, filemode=a ) def printLogs(self): 輸出到屏幕 :return: console = logging.StreamHandler() console.setLevel(logging.INFO) formatter = logging.Formatter(%(name)-12s: %(levelname)-8s %(message)s) console.setFormatter(formatter) logging.getLogger().addHandler(console)def logger(): 測試用例 :return: logger = Logger() logger.printLogs() logging.debug(This is debug message!) logging.info(This is info message!) logging.warning(This is warning message!) logging.error(This is error message!)def loggerByConfig(): 通過讀取日誌配置文件記載日誌 :return: logging.config.fileConfig(logger.conf) logger = logging.getLogger(example01) logger.debug(This is debug message!) logger = logging.getLogger(example02) logger.error(This is error message!)if __name__ == __main__: logger() # loggerByConfig()

logger.conf配置樣例:

[loggers]keys=root,example01,example02[logger_root]level=DEBUGhandlers=hand01,hand02[logger_example01]handlers=hand01,hand02qualname=example01propagate=0[logger_example02]handlers=hand01,hand03qualname=example02propagate=0###############################################[handlers]keys=hand01,hand02,hand03[handler_hand01]class=StreamHandlerlevel=INFOformatter=form02args=(sys.stderr,)[handler_hand02]class=FileHandlerlevel=DEBUGformatter=form01args=(error.log, a)[handler_hand03]class=handlers.RotatingFileHandlerlevel=INFOformatter=form02args=(error.log, a, 10*1024*1024, 5)###############################################[formatters]keys=form01,form02[formatter_form01]format=%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)sdatefmt=%Y-%m-%d %H:%M:%S[formatter_form02]format=%(name)-12s: %(levelname)-8s %(message)sdatefmt=%Y-%m-%d %H:%M:%S

推薦閱讀:

Python跳一跳之樹莓派純硬體實現
Python Sequence Types-list, tuple and range
史上最全的python滲透測試工具合集
Python出現ValueError: need more than 1 value to unpack 的原因是什麼?

TAG:Python |