轉載:http://www.javashuo.com/article/p-xhfakruo-c.html
用Python寫代碼的時候,在想看的地方寫個print xx 就能在控制檯上顯示打印信息,這樣子就能知道它是什麼了,可是當我須要看大量的地方或者在一個文件中查看的時候,這時候print就不大方便了,因此Python引入了logging模塊來記錄我想要的信息。
print也能夠輸入日誌,logging相對print來講更好控制輸出在哪一個地方,怎麼輸出及控制消息級別來過濾掉那些不須要的信息。html
import logging # 引入logging模塊 # 將信息打印到控制檯上 logging.debug(u"蒼井空") logging.info(u"麻生希") logging.warning(u"小澤瑪利亞") logging.error(u"桃谷繪里香") logging.critical(u"瀧澤蘿拉")
回顯:函數
上面能夠看到只有後面三個能打印出來this
默認生成的root logger的level是logging.WARNING,低於該級別的就不輸出了線程
級別排序:CRITICAL > ERROR > WARNING > INFO > DEBUGdebug
debug : 打印所有的日誌,詳細的信息,一般只出如今診斷問題上日誌
info : 打印info,warning,error,critical級別的日誌,確認一切按預期運行code
warning : 打印warning,error,critical級別的日誌,一個跡象代表,一些意想不到的事情發生了,或代表一些問題在不久的未來(例如。磁盤空間低」),這個軟件還能按預期工做orm
error : 打印error,critical級別的日誌,更嚴重的問題,軟件沒能執行一些功能htm
critical : 打印critical級別,一個嚴重的錯誤,這代表程序自己可能沒法繼續運行對象
這時候,若是須要顯示低於WARNING級別的內容,能夠引入NOTSET級別來顯示:
import logging # 引入logging模塊 logging.basicConfig(level=logging.NOTSET) # 設置日誌級別 logging.debug(u"若是設置了日誌級別爲NOTSET,那麼這裏能夠採起debug、info的級別的內容也能夠顯示在控制檯上了")
Logging.Formatter:這個類配置了日誌的格式,在裏面自定義設置日期和時間,輸出日誌的時候將會按照設置的格式顯示內容。
Logging.Logger:Logger是Logging模塊的主體,進行如下三項工做:
import logging # 引入logging模塊 logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s') # logging.basicConfig函數對日誌的輸出格式及方式作相關配置 # 因爲日誌基本配置中級別設置爲DEBUG,因此一下打印信息將會所有顯示在控制檯上 logging.info('this is a loggging info message') logging.debug('this is a loggging debug message') logging.warning('this is loggging a warning message') logging.error('this is an loggging error message') logging.critical('this is a loggging critical message')
上面代碼經過logging.basicConfig函數進行配置了日誌級別和日誌內容輸出格式;由於級別爲DEBUG,因此會將DEBUG級別以上的信息都輸出顯示再控制檯上。
回顯:
import logging # 引入logging模塊 import os.path import time # 第一步,建立一個logger logger = logging.getLogger() logger.setLevel(logging.INFO) # Log等級總開關 # 第二步,建立一個handler,用於寫入日誌文件 rq = time.strftime('%Y%m%d%H%M', time.localtime(time.time())) log_path = os.path.dirname(os.getcwd()) + '/Logs/' log_name = log_path + rq + '.log' logfile = log_name fh = logging.FileHandler(logfile, mode='w') fh.setLevel(logging.DEBUG) # 輸出到file的log等級的開關 # 第三步,定義handler的輸出格式 formatter = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s") fh.setFormatter(formatter) # 第四步,將logger添加到handler裏面 logger.addHandler(fh) # 日誌 logger.debug('this is a logger debug message') logger.info('this is a logger info message') logger.warning('this is a logger warning message') logger.error('this is a logger error message') logger.critical('this is a logger critical message')
回顯(打開同一目錄下生成的文件):
只要在輸入到日誌中的第二步和第三步插入一個handler輸出到控制檯:
建立一個handler,用於輸出到控制檯
ch = logging.StreamHandler()
ch.setLevel(logging.WARNING) # 輸出到console的log等級的開關
第四步和第五步分別加入如下代碼便可
ch.setFormatter(formatter)
logger.addHandler(ch)
%(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: 打印日誌信息
import os.path import time import logging # 建立一個logger logger = logging.getLogger() logger.setLevel(logging.INFO) # Log等級總開關 # 建立一個handler,用於寫入日誌文件 rq = time.strftime('%Y%m%d%H%M', time.localtime(time.time())) log_path = os.path.dirname(os.getcwd()) + '/Logs/' log_name = log_path + rq + '.log' logfile = log_name fh = logging.FileHandler(logfile, mode='w') fh.setLevel(logging.DEBUG) # 輸出到file的log等級的開關 # 定義handler的輸出格式 formatter = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s") fh.setFormatter(formatter) logger.addHandler(fh) # 使用logger.XX來記錄錯誤,這裏的"error"能夠根據所須要的級別進行修改 try: open('/path/to/does/not/exist', 'rb') except (SystemExit, KeyboardInterrupt): raise except Exception, e: logger.error('Failed to open file', exc_info=True)
回顯(存儲在文件中):
若是須要將日誌不上報錯誤,僅記錄,能夠將exc_info=False,回顯以下:
#warning_output.py import logging def write_warning(): logging.warning(u"記錄文件warning_output.py的日誌") #error_output.py import logging def write_error(): logging.error(u"記錄文件error_output.py的日誌") #main.py import logging import warning_output import error_output def write_critical(): logging.critical(u"記錄文件main.py的日誌") warning_output.write_warning() # 調用warning_output文件中write_warning方法 write_critical() error_output.write_error() # 調用error_output文件中write_error方法
回顯:
從上面來看,日誌的輸出順序和模塊執行順序是一致的。
# coding:utf-8 import logging import time import re from logging.handlers import TimedRotatingFileHandler from logging.handlers import RotatingFileHandler def backroll(): #日誌打印格式 log_fmt = '%(asctime)s\tFile \"%(filename)s\",line %(lineno)s\t%(levelname)s: %(message)s' formatter = logging.Formatter(log_fmt) #建立TimedRotatingFileHandler對象 log_file_handler = TimedRotatingFileHandler(filename="ds_update", when="M", interval=2, backupCount=2) #log_file_handler.suffix = "%Y-%m-%d_%H-%M.log" #log_file_handler.extMatch = re.compile(r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}.log$") log_file_handler.setFormatter(formatter) logging.basicConfig(level=logging.INFO) log = logging.getLogger() log.addHandler(log_file_handler) #循環打印日誌 log_content = "test log" count = 0 while count < 30: log.error(log_content) time.sleep(20) count = count + 1 log.removeHandler(log_file_handler) if __name__ == "__main__": backroll()
filename:日誌文件名的prefix;
when:是一個字符串,用於描述滾動週期的基本單位,字符串的值及意義以下:
「S」: Seconds
「M」: Minutes
「H」: Hours
「D」: Days
「W」: Week day (0=Monday)
「midnight」: Roll over at midnight
interval: 滾動週期,單位有when指定,好比:when=’D’,interval=1,表示天天產生一個日誌文件
backupCount: 表示日誌文件的保留個數