python之強大的日誌模組__python

來源:互聯網
上載者:User
作者:txw1958 | 出處:部落格園 | 2011/10/21 19:41:55 | 閱讀 43次 1.簡單的將日誌列印到螢幕  

import logging

logging.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 logging

logging.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 message
Sun, 24 May 2009 21:48:54 demo2.py[line:12] INFO This is info message
Sun, 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 logging

logging.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 message
root        : WARNING  This is warning message

./myapp.log檔案中內容為:
Sun, 24 May 2009 21:48:54 demo2.py[line:11] DEBUG This is debug message
Sun, 24 May 2009 21:48:54 demo2.py[line:12] INFO This is info message
Sun, 24 May 2009 21:48:54 demo2.py[line:13] WARNING This is warning message

4.logging之日誌復原

import logging
from logging.handlers import RotatingFileHandler

#################################################################################################
#定義一個RotatingFileHandler,最多備份5個記錄檔,每個記錄檔最大10M
Rthandler = 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=DEBUG
handlers=hand01,hand02

[logger_example01]
handlers=hand01,hand02
qualname=example01
propagate=0

[logger_example02]
handlers=hand01,hand03
qualname=example02
propagate=0

###############################################

[handlers]
keys=hand01,hand02,hand03

[handler_hand01]
class=StreamHandler
level=INFO
formatter=form02
args=(sys.stderr,)

[handler_hand02]
class=FileHandler
level=DEBUG
formatter=form01
args=('myapp.log', 'a')

[handler_hand03]
class=handlers.RotatingFileHandler
level=INFO
formatter=form02
args=('myapp.log', 'a', 10*1024*1024, 5)

###############################################

[formatters]
keys=form01,form02

[formatter_form01]
format=%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s
datefmt=%a, %d %b %Y %H:%M:%S

[formatter_form02]
format=%(name)-12s: %(levelname)-8s %(message)s
datefmt=

上例3:

import logging
import logging.config

logging.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')

上例4:

import logging
import logging.config

logging.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是安全執行緒的 7.logging重新導向strerr,strout
import loggingimport sys class StreamToLogger(object):   """   Fake file-like stream object that redirects writes to a logger instance.   """   def __init__(self, logger, log_level=logging.INFO):      self.logger = logger      self.log_level = log_level      self.linebuf = ''    def write(self, buf):      for line in buf.rstrip().splitlines():         self.logger.log(self.log_level, line.rstrip()) logging.basicConfig(   level=logging.DEBUG,   format='%(asctime)s:%(levelname)s:%(name)s:%(message)s',   filename="out.log",   filemode='a') stdout_logger = logging.getLogger('STDOUT')sl = StreamToLogger(stdout_logger, logging.INFO)sys.stdout = sl stderr_logger = logging.getLogger('STDERR')sl = StreamToLogger(stderr_logger, logging.ERROR)sys.stderr = sl print "Test to standard out"raise Exception('Test to standard error')



We define a custom file-like object called StreamToLogger object which sends anything written to it to a logger instead. We then create two instances of that object and replace sys.stdout and sys.stderr with our fake file-like instances.

The output logfile looks like this:

2011-08-14 14:46:20,573:INFO:STDOUT:Test to standard out  2011-08-14 14:46:20,573:ERROR:STDERR:Traceback (most recent call last):  2011-08-14 14:46:20,574:ERROR:STDERR:  File "redirect.py", line 33, in   2011-08-14 14:46:20,574:ERROR:STDERR:raise Exception('Test to standard error')  2011-08-14 14:46:20,574:ERROR:STDERR:Exception  2011-08-14 14:46:20,574:ERROR:STDERR::  2011-08-14 14:46:20,574:ERROR:STDERR:Test to standard error  2011-08-14 14:46:20,573:INFO:STDOUT:Test to standard out2011-08-14 14:46:20,573:ERROR:STDERR:Traceback (most recent call last):2011-08-14 14:46:20,574:ERROR:STDERR:  File "redirect.py", line 33, in 2011-08-14 14:46:20,574:ERROR:STDERR:raise Exception('Test to standard error')2011-08-14 14:46:20,574:ERROR:STDERR:Exception2011-08-14 14:46:20,574:ERROR:STDERR::2011-08-14 14:46:20,574:ERROR:STDERR:Test to standard error

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.