簡單的將日志打印到屏幕
import logging
logging.debug('debug message')
logging.info('info message')
logging.warning('warning message')
logging.error('error message')
logging.critical('critical message')
輸出:
WARNING:root:warning message
ERROR:root:error message
CRITICAL:root:critical message
可見,默認情況下Python的logging模塊將日志打印到了標準輸出中,且只顯示了大于等于WARNING級別的日志,這說明默認的日志級別設置為WARNING(日志級別等級CRITICAL > ERROR > WARNING > INFO > DEBUG ),默認日志格式如上
靈活配置日志級別,日志格式,輸出位置 (將日志寫入文件)
import logging
logging.basicConfig(filename='myapp.log',
filemode='w',
level=logging.CRITICAL,
format=('%(asctime)s %(filename)s %(levelname)s %(message)s'),
datefmt="%m/%d/%Y %H:%M:%S %p")
logging.debug("debug message")
logging.info("info message")
logging.warning("warning message")
logging.error("error message")
logging.critical("critical message")
查看文件:
04/06/2017 11:16:35 AM test13.py CRITICAL critical message
可見在logging.basicConfig()函數(shù)中可通過具體參數(shù)來更改logging模塊默認行為,可用參數(shù)有
filename:用指定的文件名創(chuàng)建FiledHandler(后邊會具體講解handler的概念),這樣日志會被存儲在指定的文件中。
filemode:文件打開方式,在指定了filename時使用這個參數(shù),默認值為“a”還可指定為“w”。
format:指定handler使用的日志顯示格式。
datefmt:指定日期時間格式。
level:設置rootlogger(后邊會講解具體概念)的日志級別
format參數(shù)中可能用到的格式化串:
%(name)s Logger的名字
%(levelno)s 數(shù)字形式的日志級別
%(levelname)s 文本形式的日志級別
%(pathname)s 調(diào)用日志輸出函數(shù)的模塊的完整路徑名,可能沒有
%(filename)s 調(diào)用日志輸出函數(shù)的模塊的文件名
%(module)s 調(diào)用日志輸出函數(shù)的模塊名
%(funcName)s 調(diào)用日志輸出函數(shù)的函數(shù)名
%(asctime)s 字符串形式的當前時間。默認格式是 “2003-07-08 16:49:45,896”。逗號后面的是毫秒
%(message)s用戶輸出的消息
注意:basicConfig是單實例模式,創(chuàng)建時候只有一個logger對象。還是使用下面的方法吧...
同時輸出至文件和屏幕
Python 使用logging模塊記錄日志涉及四個主要類,使用官方文檔中的概括最為合適:
logger:提供日志接口,供應用代碼使用。logger最長用的操作有兩類:配置和發(fā)送日志消息??梢酝ㄟ^logging.getLogger(name)獲取logger對象,如果不指定name則返回root對象,多次使用相同的name調(diào)用getLogger方法返回同一個logger對象。
handler:將日志記錄(log record)發(fā)送到合適的目的地(destination),比如文件,socket等。一個logger對象可以通過addHandler方法添加0到多個handler,每個handler又可以定義不同日志級別,以實現(xiàn)日志分級過濾顯示。
filter:提供一種優(yōu)雅的方式?jīng)Q定一個日志記錄是否發(fā)送到handler。
formatter:指定日志記錄輸出的具體格式。formatter的構(gòu)造方法需要兩個參數(shù):消息的格式字符串和日期字符串,這兩個參數(shù)都是可選的。
import logging
#設置輸出流
ch=logging.StreamHandler() #屏幕輸出
ch.setLevel(logging.ERROR) #屏幕輸出級別
fh=logging.FileHandler("test_log",'w') #文件輸出,默認為‘a(chǎn)’
fh.setLevel(logging.DEBUG)
#設置輸出流格式并將格式加入到輸出流
ch_formatter=logging.Formatter("%(asctime)s %(filename)s %(message)s")
fh_formatter=logging.Formatter('%(asctime)s-%(name)s-%(message)s')
ch.setFormatter(ch_formatter) #添加到輸出流
fh.setFormatter(fh_formatter) #添加到輸出流
#創(chuàng)建一個log并添加定義的輸出流
log=logging.getLogger("mylog")
log.setLevel(logging.WARNING) #全局設置,logging.INFO將不會被打印
log.addHandler(ch)
log.addHandler(fh)
log.debug('debugmessage')
log.info('infomessage')
log.warning('warningmessage')
log.error('error message')
log.critical('critical message')
屏幕輸出:
2017-04-06 12:07:17,911 logging多輸出.py error message
2017-04-06 12:07:17,911 logging多輸出.py critical message
文件test_log輸出:
2017-04-06 12:07:17,911-mylog-warningmessage
2017-04-06 12:07:17,911-mylog-error message
2017-04-06 12:07:17,911-mylog-critical message
文件日志自動截斷
import logging,time
from logging import handlers
#根據(jù)文件大小或時間間隔來截斷文件
# fh=handlers.RotatingFileHandle(filename='rotatingfile_log',maxBytes=10,backupCount=3,encoding='utf-8')
fh=handlers.TimedRotatingFileHandler(filename='rotatingfile_log',when='s',
interval=5,backupCount=3,encoding='utf-8')
# formatter=logging.Formatter('%(asctime)s %(filename)s %(message)s')
formatter=logging.Formatter(fmt='%(asctime)s %(filename)s %(message)s',datefmt='%Y-%m-%d %H:%M:%S')
fh.setFormatter(formatter)
fh.setLevel(logging.DEBUG)
logger=logging.getLogger('test_again')
logger.addHandler(fh)
logger.debug("123")
time.sleep(2)
logger.info("456")
time.sleep(2)
logger.warning("789")
time.sleep(2)
logger.error("abc")
time.sleep(2)
logger.critical("000")
時間截斷的when參數(shù)是一個字符串。表示時間間隔,不區(qū)分大小寫
S秒 M分 H小時 D天
midnight每天凌晨