python模組學習 logging

來源:互聯網
上載者:User

標籤:

1.簡單的將日誌列印到螢幕

import logginglogging.debug(‘This is debug message‘)logging.info(‘This is info message‘)logging.warning(‘This is warning message‘)   螢幕上列印:WARNING:root:This is warning message

預設情況下,logging將日誌列印到螢幕,記錄層級為WARNING;
記錄層級大小關係為:CRITICAL > ERROR > WARNING > INFO > DEBUG > NOTSET,當然也可以自己定義記錄層級。

2.通過logging.basicConfig函數對日誌的輸出格式及方式做相關配置

import logginglogging.basicConfig(level=logging.DEBUG,                format=‘%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s‘,                datefmt=‘%a, %d %b %Y %H:%M:%S‘,                filename=‘myapp.log‘,                filemode=‘w‘)    logging.debug(‘This is debug message‘)logging.info(‘This is info message‘)logging.warning(‘This is warning message‘)   ./myapp.log檔案中內容為:Sun, 24 May 2009 21:48:54 demo2.py[line:11] DEBUG This is debug messageSun, 24 May 2009 21:48:54 demo2.py[line:12] INFO This is info messageSun, 24 May 2009 21:48:54 demo2.py[line:13] WARNING This is warning message

logging.basicConfig函數各參數:
filename: 指定記錄檔名
filemode: 和file函數意義相同,指定記錄檔的開啟模式,‘w‘或‘a‘
format: 指定輸出的格式和內容,format可以輸出很多有用資訊,如上例所示:
%(levelno)s: 列印記錄層級的數值
%(levelname)s: 列印記錄層級名稱
%(pathname)s: 列印當前執行程式的路徑,其實就是sys.argv[0]
%(filename)s: 列印當前執行程式名
%(funcName)s: 列印日誌的當前函數
%(lineno)d: 列印日誌的當前行號
%(asctime)s: 列印日誌的時間
%(thread)d: 列印線程ID
%(threadName)s: 列印線程名稱
%(process)d: 列印進程ID
%(message)s: 列印日誌資訊
datefmt: 指定時間格式,同time.strftime()
level: 設定記錄層級,預設為logging.WARNING
stream: 指定將日誌的輸出資料流,可以指定輸出到sys.stderr,sys.stdout或者檔案,預設輸出到sys.stderr,當stream和filename同時指定時,stream被忽略

3.將日誌同時輸出到檔案和螢幕

import logginglogging.basicConfig(level=logging.DEBUG,                format=‘%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s‘,                datefmt=‘%a, %d %b %Y %H:%M:%S‘,                filename=‘myapp.log‘,                filemode=‘w‘)##################################################################################################定義一個StreamHandler,將INFO層級或更高的日誌資訊列印到標準錯誤,並將其添加到當前的Tlog對象#console = logging.StreamHandler()console.setLevel(logging.INFO)formatter = logging.Formatter(‘%(name)-12s: %(levelname)-8s %(message)s‘)console.setFormatter(formatter)logging.getLogger(‘‘).addHandler(console)#################################################################################################logging.debug(‘This is debug message‘)logging.info(‘This is info message‘)logging.warning(‘This is warning message‘)   螢幕上列印:root        : INFO     This is info messageroot        : WARNING  This is warning message ./myapp.log檔案中內容為:Sun, 24 May 2009 21:48:54 demo2.py[line:11] DEBUG This is debug messageSun, 24 May 2009 21:48:54 demo2.py[line:12] INFO This is info messageSun, 24 May 2009 21:48:54 demo2.py[line:13] WARNING This is warning message

4.logging之日誌復原

import loggingfrom logging.handlers import RotatingFileHandler##################################################################################################定義一個RotatingFileHandler,最多備份5個記錄檔,每個記錄檔最大10MRthandler = RotatingFileHandler(‘myapp.log‘, maxBytes=10*1024*1024,backupCount=5)Rthandler.setLevel(logging.INFO)formatter = logging.Formatter(‘%(name)-12s: %(levelname)-8s %(message)s‘)Rthandler.setFormatter(formatter)logging.getLogger(‘‘).addHandler(Rthandler)################################################################################################

從上例和本例可以看出,logging有一個Tlog的主對象,其它處理方式都是通過addHandler添加進去的。
logging的幾種handle方式如下:

logging.StreamHandler: 日誌輸出到流,可以是sys.stderr、sys.stdout或者檔案 logging.FileHandler: 日誌輸出到檔案

日誌復原方式,實際使用時用RotatingFileHandler和TimedRotatingFileHandler logging.handlers.BaseRotatingHandler logging.handlers.RotatingFileHandler logging.handlers.TimedRotatingFileHandler

logging.handlers.SocketHandler: 遠程輸出日誌到TCP/IP sockets

logging.handlers.DatagramHandler: 遠程輸出日誌到UDP sockets

logging.handlers.SMTPHandler: 遠程輸出日誌到郵件地址

logging.handlers.SysLogHandler: 日誌輸出到syslog

logging.handlers.NTEventLogHandler: 遠程輸出日誌到Windows NT/2000/XP的事件記錄

logging.handlers.MemoryHandler: 日誌輸出到記憶體中的制定buffer

logging.handlers.HTTPHandler: 通過"GET"或"POST"遠程輸出到HTTP伺服器

 

由於StreamHandler和FileHandler是常用的Tlog方式,所以直接包含在logging模組中,而其他方式則包含在logging.handlers模組中,
上述其它處理方式的使用請參見python2.5手冊!

5.通過logging.config模組配置日誌

#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=(‘myapp.log‘, ‘a‘) [handler_hand03]class=handlers.RotatingFileHandlerlevel=INFOformatter=form02args=(‘myapp.log‘, ‘a‘, 10*1024*1024, 5) ############################################### [formatters]keys=form01,form02 [formatter_form01]format=%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)sdatefmt=%a, %d %b %Y %H:%M:%S [formatter_form02]format=%(name)-12s: %(levelname)-8s %(message)sdatefmt=
import loggingimport logging.configlogging.config.fileConfig("logger.conf")logger = logging.getLogger("example01")logger.debug(‘This is debug message‘)logger.info(‘This is info message‘)logger.warning(‘This is warning message‘)
import loggingimport logging.configlogging.config.fileConfig("logger.conf")logger = logging.getLogger("example02")logger.debug(‘This is debug message‘)logger.info(‘This is info message‘)logger.warning(‘This is warning message‘)

6.logging是安全執行緒的

from:http://blog.csdn.net/yatere/article/details/6655445

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.