亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

python中l(wèi)ogging模塊的一些簡單用法的使用

 更新時間:2019年02月22日 09:36:47   作者:加班使我變丑智商下降  
這篇文章主要介紹了python中l(wèi)ogging模塊的一些簡單用法的使用,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

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

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

1、日志級別

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

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

debug : 打印全部的日志,詳細的信息,通常只出現(xiàn)在診斷問題上

info : 打印info,warning,error,critical級別的日志,確認一切按預(yù)期運行

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

error : 打印error,critical級別的日志,更嚴(yán)重的問題,軟件沒能執(zhí)行一些功能

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

這時候,如果需要顯示低于WARNING級別的內(nèi)容,可以引入NOTSET級別來顯示:

import logging # 引入logging模塊
logging.basicConfig(level=logging.NOTSET) # 設(shè)置日志級別
logging.debug(u"如果設(shè)置了日志級別為NOTSET,那么這里可以采取debug、info的級別的內(nèi)容也可以顯示在控制臺上了")

回顯:

2、部分名詞解釋

Logging.Formatter:這個類配置了日志的格式,在里面自定義設(shè)置日期和時間,輸出日志的時候?qū)凑赵O(shè)置的格式顯示內(nèi)容。

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

1. 為程序提供記錄日志的接口
2. 判斷日志所處級別,并判斷是否要過濾
3. 根據(jù)其日志級別將該條日志分發(fā)給不同handler

常用函數(shù)有:
Logger.setLevel() 設(shè)置日志級別
Logger.addHandler() 和 Logger.removeHandler() 添加和刪除一個Handler
Logger.addFilter() 添加一個Filter,過濾作用
Logging.Handler:Handler基于日志級別對日志進行分發(fā),如設(shè)置為WARNING級別的Handler只會處理WARNING及以上級別的日志。

常用函數(shù)有:
setLevel() 設(shè)置級別
setFormatter() 設(shè)置Formatter

3、日志輸出-控制臺

import logging # 引入logging模塊
logging.basicConfig(level=logging.DEBUG,
          format='%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s') # logging.basicConfig函數(shù)對日志的輸出格式及方式做相關(guān)配置
# 由于日志基本配置中級別設(shè)置為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函數(shù)進行配置了日志級別和日志內(nèi)容輸出格式;因為級別為DEBUG,所以會將DEBUG級別以上的信息都輸出顯示再控制臺上。

回顯:

4、日志輸出-文件

import logging # 引入logging模塊
import os.path
import time
# 第一步,創(chuàng)建一個logger
logger = logging.getLogger()
logger.setLevel(logging.INFO) # Log等級總開關(guān)
# 第二步,創(chuàng)建一個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等級的開關(guān)
# 第三步,定義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輸出到控制臺:

創(chuàng)建一個handler,用于輸出到控制臺

ch = logging.StreamHandler()
ch.setLevel(logging.WARNING) # 輸出到console的log等級的開關(guān)

第四步和第五步分別加入以下代碼即可

ch.setFormatter(formatter)
logger.addHandler(ch)

6、format常用格式說明

  • %(levelno)s: 打印日志級別的數(shù)值
  • %(levelname)s: 打印日志級別名稱
  • %(pathname)s: 打印當(dāng)前執(zhí)行程序的路徑,其實就是sys.argv[0]
  • %(filename)s: 打印當(dāng)前執(zhí)行程序名
  • %(funcName)s: 打印日志的當(dāng)前函數(shù)
  • %(lineno)d: 打印日志的當(dāng)前行號
  • %(asctime)s: 打印日志的時間
  • %(thread)d: 打印線程ID
  • %(threadName)s: 打印線程名稱
  • %(process)d: 打印進程ID
  • %(message)s: 打印日志信息

7、捕捉異常,用traceback記錄

import os.path
import time
import logging
# 創(chuàng)建一個logger
logger = logging.getLogger()
logger.setLevel(logging.INFO) # Log等級總開關(guān)

# 創(chuàng)建一個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等級的開關(guān)

# 定義handler的輸出格式
formatter = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s")
fh.setFormatter(formatter)
logger.addHandler(fh)
# 使用logger.XX來記錄錯誤,這里的"error"可以根據(jù)所需要的級別進行修改
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、多模塊調(diào)用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() # 調(diào)用warning_output文件中write_warning方法
write_critical()
error_output.write_error() # 調(diào)用error_output文件中write_error方法

回顯:

從上面來看,日志的輸出順序和模塊執(zhí)行順序是一致的。

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)
  #創(chuàng)建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)
  #循環(huán)打印日志
  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,表示每天產(chǎn)生一個日志文件

backupCount: 表示日志文件的保留個數(shù)

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論