python中logging日志模塊詳解


博客轉自: https://www.cnblogs.com/CJOKER/p/8295272.html

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

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

1、日志級別

import logging  # 引入logging模塊
# 將信息打印到控制台上
logging.debug(u"蒼井空")
logging.info(u"麻生希")
logging.warning(u"小澤瑪利亞")
logging.error(u"桃谷繪里香")
logging.critical(u"瀧澤蘿拉")

回顯:

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

默認生成的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、部分名詞解釋

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及以上級別的日志。
常用函數有:
setLevel() 設置級別
setFormatter() 設置Formatter

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

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

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, 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:是一個字符串,用於描述滾動周期的基本單位,字符串的值及意義如下: 
“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: 表示日志文件的保留個數


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM