Python通過logging.config.fileConfig()配置日誌
level:
CRITICAL > ERROR > WARNING > INFO > DEBUG > NOTSET
class:
handlers.RotatingFileHandler(重定向到文件,並設置單個日誌文件的大小和日誌文件個數)
handlers.TimedRotatingFileHandler(重定向到文件,並設置單個日誌切分時間和日誌文件個數)
StreamHandler(將日誌輸出到控制檯)
FileHandler(將日誌信息輸出保存到文件)
配置文件logging.conf信息如下:
#logger定義與配置,必須包含root
[loggers]
keys=root,eb_nfvo
[logger_root]
level=DEBUG #日誌等級
handlers=eb_nfvo_stream
[logger_eb_nfvo]
handlers=eb_nfvo_stream,eb_nfvo_timed_rotating_file #必須引用下面配置過的handler
qualname=eb_nfvo #logger層級中的名字,應用程序中用logging.getLogger('eb_nfvo')使用
propagate=0 #通常爲0
#handler定義與配置(定義日誌打印的位置,如:控制檯輸出、文件輸出)
[handlers]
keys=eb_nfvo_stream,eb_nfvo_timed_rotating_file
[handler_eb_nfvo_stream]
class=StreamHandler #定義打印日誌的方式
args=(sys.stderr,) #給class傳入的參數,元組形式(class類型不同,傳參方式不同)
level=DEBUG #與logger中的level保持一致
formatter=nfvo_form
[handler_eb_nfvo_timed_rotating_file]
class=handlers.TimedRotatingFileHandler
args=('../logs/eb_nfvo.log','H',8,270) #重定向到文件,每8小時切分一次,最多270個(90天)
level=DEBUG鄭州婦科醫院 http://www.hnzzkd.com/
formatter=nfvo_form #指定日誌格式,需指定下面已經定義好的
#formatter定義與配置(設置打印日誌的格式)
[formatters]
keys=nfvo_form
[formatter_nfvo_form]
format=%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s
datefmt=%Y-%m-%d %H:%M:%S
程序中引用的代碼如下:
#! /usr/bin/python2
import logging
import logging.config
logging.config.fileConfig('configure/logging.conf') #配置文件的路徑
logger = logging.getLogger('eb_nfvo')