天天看點

Python logging子產品使用記錄

   Python logging子產品使用記錄    

2015-11-15 11:48 狂師  閱讀(308)  評論(0) 編輯 收藏    

1.簡單的将日志列印到螢幕

 warning message           

預設情況下,logging将日志列印到螢幕,日志級别為WARNING;

日志級别大小關系為:CRITICAL > ERROR > WARNING > INFO > DEBUG > NOTSET,當然也可以自己定義日志級别。

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

 1 import logging 2  3 logging.basicConfig(level=logging.DEBUG, 4                 format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', 5                 datefmt='%a, %d %b %Y %H:%M:%S', 6                 filename='myapp.log', 7                 filemode='w') 8      9 logging.debug('This is debug message')10 logging.info('This is info message')11 logging.warning('This is warning message')12  13 ./myapp.log檔案中内容為:14 Sun, 24 May 2009 21:48:54 demo2.py[line:11] DEBUG This is debug message15 Sun, 24 May 2009 21:48:54 demo2.py[line:12] INFO This is info message16 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.将日志同時輸出到檔案和螢幕

 1 import logging 2  3 logging.basicConfig(level=logging.DEBUG, 4                 format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', 5                 datefmt='%a, %d %b %Y %H:%M:%S', 6                 filename='myapp.log', 7                 filemode='w') 8  9 #################################################################################################10 #定義一個StreamHandler,将INFO級别或更高的日志資訊列印到标準錯誤,并将其添加到目前的日志處理對象#11 console = logging.StreamHandler()12 console.setLevel(logging.INFO)13 formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')14 console.setFormatter(formatter)15 logging.getLogger('').addHandler(console)16 #################################################################################################17 18 logging.debug('This is debug message')19 logging.info('This is info message')20 logging.warning('This is warning message')21  22 螢幕上列印:23 root        : INFO     This is info message24 root        : WARNING  This is warning message25 ./myapp.log檔案中内容為:26 Sun, 24 May 2009 21:48:54 demo2.py[line:11] DEBUG This is debug message27 Sun, 24 May 2009 21:48:54 demo2.py[line:12] INFO This is info message28 Sun, 24 May 2009 21:48:54 demo2.py[line:13] WARNING This is warning message           

4.logging之日志復原

 1 import logging 2 from logging.handlers import RotatingFileHandler 3  4 ################################################################################################# 5 #定義一個RotatingFileHandler,最多備份5個日志檔案,每個日志檔案最大10M 6 Rthandler = RotatingFileHandler('myapp.log', maxBytes=10*1024*1024,backupCount=5) 7 Rthandler.setLevel(logging.INFO) 8 formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s') 9 Rthandler.setFormatter(formatter)10 logging.getLogger('').addHandler(Rthandler)11 ################################################################################################           

從上例和本例可以看出,logging有一個日志處理的主對象,其它處理方式都是通過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伺服器

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 loggingimport 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 loggingimport 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')           
  • 分類            Python