記錄一下自己用到的python logging

來源:互聯網
上載者:User

標籤:

  最近想把自己零零散散寫的代碼嵌成一個應用,要考慮到各方面的debug,把logging看了一下,把用到的記下來。

  • 將日誌列印到螢幕
import logginglogging.debug(u‘調試‘)logging.info(u‘運行‘)logging.warning(u‘警告‘)#運行顯示:#WARNING:root:警告 
#預設情況下,logging列印WARNING層級以上的,並列印到螢幕。
#記錄層級大小關係 CRITICAL > ERROR > WARNING > INFO > DEBUG > NOTSET(預設),並且可以自訂。
  • basicConfig函數配置日誌輸出
#-*- coding:utf-8 -*-import logginglogging.basicConfig(level=logging.DEBUG,                format=u‘%(asctime)s 檔案:%(filename)s [第 %(lineno)d 行] 等級: %(levelname)s 資訊: %(message)s‘,                datefmt=‘ %Y %b %d  %H:%M:%S,%a‘,                filename=‘guapeng.log‘,                filemode=‘w‘)    logging.debug(u‘調試‘)logging.info(u‘資訊‘)logging.warning(u‘警告‘)#guapeng.log檔案顯示如下#2015 Jul 27 16:22:26,Mon 檔案:testlog.py [第 10 行] 等級: DEBUG 資訊: 調試#2015 Jul 27 16:22:26,Mon 檔案:testlog.py [第 11 行] 等級: INFO 資訊: 資訊#2015 Jul 27 16:22:26,Mon 檔案:testlog.py [第 12 行] 等級: WARNING 資訊: 警告#basicConfig參數說明:#filename: 指定記錄檔名#filemode: 開啟模式,‘w‘或‘a‘#format: 指定輸出的格式和內容,一些format預設的參數:#  %(levelno)s: 記錄層級數值#  %(levelname)s: 記錄層級名稱#  %(pathname)s: 當前執行程式的路徑,相當於sys.argv[0]#  %(filename)s: 當前執行程式名(注意這裡與log檔案名稱是不同的)#  %(funcName)s: 當前執行函數#  %(lineno)d: 當前行號#  %(asctime)s: 目前時間#  %(thread)d: 線程ID#  %(threadName)s: 線程名稱#  %(process)d: 進程ID#  %(message)s: 日誌資訊#datefmt: 指定時間格式,與time.strftime()一樣#level: 設定列印記錄層級,預設為logging.WARNING,上例為DEBUG,故大於DEBUG的都輸出到log檔案。#stream: 指定日誌的輸出方式,預設輸出到sys.stderr(螢幕),當stream和filename同時指定時,stream被忽略
  • 將debug資訊列印打log檔案,將info資訊列印到螢幕
#-*- coding:utf-8 -*-import logginglogging.basicConfig(level=logging.DEBUG,                format=u‘%(asctime)s 檔案:%(filename)s [第 %(lineno)d 行] 等級: %(levelname)s 資訊: %(message)s‘,                datefmt=‘ %Y %b %d  %H:%M:%S,%a‘,                filename=‘guapeng.log‘,                filemode=‘w‘)#定義一個StreamHandler,將INFO層級的資訊列印到螢幕console = logging.StreamHandler()console.setLevel(logging.INFO)formatter = logging.Formatter(‘%(name)-12s: %(levelname)-8s %(message)s‘)console.setFormatter(formatter)log = logging.getLogger(‘‘).addHandler(console)logging.debug(u‘調試‘)logging.info(u‘資訊‘)logging.warning(u‘警告‘)#guapeng.log檔案顯示如下#2015 Jul 27 16:22:26,Mon 檔案:testlog.py [第 10 行] 等級: DEBUG 資訊: 調試#2015 Jul 27 16:22:26,Mon 檔案:testlog.py [第 11 行] 等級: INFO 資訊: 資訊#2015 Jul 27 16:22:26,Mon 檔案:testlog.py [第 12 行] 等級: WARNING 資訊: 警告#螢幕顯示如下#root        : INFO    資訊#root        : WARNING 警告
  •  用config檔案,同時實現記錄檔按天儲存,而且只存一周內的日誌。

python代碼

#-*- coding:utf-8 -*-import loggingimport logging.config#匯入設定檔logging.config.fileConfig("logging.conf") #建立loggerloggerInfo = logging.getLogger("TimeInfoLogger") #測試代碼loggerInfo.debug("debug message")loggerInfo.info("info message")loggerInfo.warn("warn message")loggerInfo.error("error message")loggerInfo.critical("critical message")

logging.conf檔案代碼

# 定義logger模組,root是父類,必需存在的,其它類自行定義。[loggers]keys=root,TimeInfoLogger# 定義handler[handlers]keys=TimeInfoHandler#定義輸出格式[formatters]keys=TimeInfoFmt#--------------------------------------------------# 實現上面定義的logger模組,必需是[logger_xxxx]這樣的形式#--------------------------------------------------# [logger_xxxx] logger_模組名稱# level     層級,層級有DEBUG、INFO、WARNING、ERROR、CRITICAL# handlers  處理類,可以有多個,用逗號分開# qualname  logger名稱,應用程式通過 logging.getLogger擷取。對於不能擷取的名稱,則記錄到root模組。# propagate 是否繼承父類的log資訊,0:否 1:是[logger_root]level=INFOhandlers=TimeInfoHandler[logger_TimeInfoLogger]level=INFOhandlers=TimeInfoHandlerpropagate=0qualname=TimeInfoLogger#--------------------------------------------------# handler#--------------------------------------------------# [handler_xxxx]# class handler類名# level 記錄層級# formatter,上面定義的formatter# args handler初始化函數參數[handler_TimeInfoHandler]class=logging.handlers.TimedRotatingFileHandlerlevel=INFOformatter=TimeInfoFmtargs=(‘C:\\Users\\tyanf\\Desktop\\error.log‘, ‘midnight‘, 1, 6)#--------------------------------------------------# 日誌格式#--------------------------------------------------# %(asctime)s       年-月-日 時-分-秒,毫秒 2013-04-26 20:10:43,745# %(filename)s      檔案名稱,不含目錄# %(pathname)s      目錄名,完整路徑# %(funcName)s      函數名# %(levelname)s     層級名# %(lineno)d        行號# %(module)s        模組名# %(message)s       訊息體# %(name)s          日誌模組名# %(process)d       進程id# %(processName)s   進程名# %(thread)d        線程id# %(threadName)s    線程名[formatter_TimeInfoFmt]format=%(asctime)s %(levelname)s %(message)sdatefmt=class=logging.Formatter
#測試時間從7月20日到7月27號,最後檔案庫顯示如下:#error.log.2015-07-21#error.log.2015-07-22#error.log.2015-07-23#error.log.2015-07-24#error.log.2015-07-25#error.log.2015-07-26#error.log#其中error.log.2015-07-20由於程式設定backupcount為6,當大於6時把最早的刪除,再添加新的記錄檔,故已經被刪除。

參考資料:

http://my.oschina.net/leejun2005/blog/126713

https://docs.python.org/2/library/logging.handlers.html

記錄一下自己用到的python logging

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.