python中logging日誌模塊詳解

用Python寫代碼的時候,在想看的地方寫個print(xx) 就能在控制檯上顯示打印信息,這樣子就能知道它是什麼了,但是當我需要看大量的地方或者在一個文件中查看的時候,這時候print就不大方便了,所以Python引入了logging模塊來記錄想要的信息。

1 日誌級別

import logging  # 引入logging模塊

# 將信息打印到控制檯上
logging.debug(u"debug")
logging.info(u"info")
logging.warning(u"warning")
logging.error(u"error")
logging.critical(u"critical")

回顯:

上面可以看到只有後面三個能打印出來

默認生成的root logger的level是logging.WARNING,低於該級別的就不輸出了

級別排序:CRITICAL > ERROR > WARNING > INFO > DEBUG

debug : 打印全部的日誌,詳細的信息,通常只出現在診斷問題上

info : 打印info,warning,error,critical級別的日誌,確認一切按預期運行

warning : 打印warning,error,critical級別的日誌,一個跡象表明,一些意想不到的事情發生了,或表明一些問題在不久的將來(例如。磁盤空間低”),這個軟件還能按預期工作

error : 打印error,critical級別的日誌,更嚴重的問題,軟件沒能執行一些功能

critical : 打印critical級別,一個嚴重的錯誤,這表明程序本身可能無法繼續運行

這時候,如果需要顯示低於WARNING級別的內容,可以引入NOTSET級別來顯示:

import logging  # 引入logging模塊

logging.basicConfig(level=logging.NOTSET)  # 設置日誌級別
logging.debug(u"如果設置了日誌級別爲NOTSET,那麼這裏可以採取debug、info的級別的內容也可以顯示在控制檯上了")

回顯:

2 部分名詞解釋

print也可以輸入日誌,logging相對print來說更好控制輸出在哪個地方,怎麼輸出及控制消息級別來過濾掉那些不需要的信息。

Logging.Formatter:這個類配置了日誌的格式,在裏面自定義設置日期和時間,輸出日誌的時候將會按照設置的格式顯示內容。

Logging.Logger:Logger是Logging模塊的主體,進行以下三項工作:

  1. 爲程序提供記錄日誌的接口

  2. 判斷日誌所處級別,並判斷是否要過濾

  3. 根據其日誌級別將該條日誌分發給不同handler

常用函數有:

Logger.setLevel() 設置日誌級別

Logger.addHandler() 和 Logger.removeHandler() 添加和刪除一個Handler

Logger.addFilter() 添加一個Filter,過濾作用

Logging.Handler:Handler基於日誌級別對日誌進行分發,如設置爲WARNING級別的Handler只會處理WARNING及以上級別的日誌。

3 日誌輸出-控制檯

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級別以上的信息都輸出顯示再控制檯上。

回顯:

4 日誌輸出-文件

import logging  # 引入logging模塊
import os
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/'
# 如果日誌目錄不存在,就創建
if not os.path.exists(log_path):
    os.mkdir(log_path)
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')

回顯(打開同一目錄下生成的文件):

文件內容:

5 日誌輸出-控制檯和文件

只要在輸入到日誌中的第二步和第三步插入一個handler輸出到控制檯:

# 創建一個handler,用於輸出到控制檯
ch = logging.StreamHandler()
ch.setLevel(logging.WARNING)  # 輸出到console的log等級的開關
# 第四步和第五步分別加入以下代碼即可
ch.setFormatter(formatter)
logger.addHandler(ch)

6 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: 打印日誌信息

7 捕捉異常,用traceback記錄

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 as e:
    logger.error('Failed to open file', exc_info=True)

回顯(存儲在文件中):

如果需要將日誌不上報錯誤,僅記錄,可以將exc_info=False,回顯如下:

8 多模塊調用logging,日誌輸出順序

  • 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方法

回顯:

從上面來看,日誌的輸出順序和模塊執行順序是一致的。

9 日誌滾動和過期刪除

# 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:是一個字符串,用於描述滾動週期的基本單位,字符串的值及意義如下:

  1. “S”: Seconds
  2. “M”: Minutes
  3. “H”: Hours
  4. “D”: Days
  5. “W”: Week day (0=Monday)
  6. “midnight”: Roll over at midnight

interval: 滾動週期,單位有when指定,比如:when=’D’,interval=1,表示每天產生一個日誌文件

backupCount: 表示日誌文件的保留個數

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章