Python中l(wèi)ogging日志庫實例詳解
logging的簡單使用
用作記錄日志,默認(rèn)分為六種日志級別(括號為級別對應(yīng)的數(shù)值)
- NOTSET(0)
- DEBUG(10)
- INFO(20)
- WARNING(30)
- ERROR(40)
- CRITICAL(50)
special
- 在自定義日志級別時注意不要和默認(rèn)的日志級別數(shù)值相同
- logging 執(zhí)行時輸出大于等于設(shè)置的日志級別的日志信息,如設(shè)置日志級別是 INFO,則 INFO、WARNING、ERROR、CRITICAL 級別的日志都會輸出。
|2logging常見對象
- Logger:日志,暴露函數(shù)給應(yīng)用程序,基于日志記錄器和過濾器級別決定哪些日志有效。
- LogRecord :日志記錄器,將日志傳到相應(yīng)的處理器處理。
- Handler :處理器, 將(日志記錄器產(chǎn)生的)日志記錄發(fā)送至合適的目的地。
- Filter :過濾器, 提供了更好的粒度控制,它可以決定輸出哪些日志記錄。
- Formatter:格式化器, 指明了最終輸出中日志記錄的格式。
|3logging基本使用
logging 使用非常簡單,使用 basicConfig() 方法就能滿足基本的使用需要;如果方法沒有傳入?yún)?shù),會根據(jù)默認(rèn)的配置創(chuàng)建Logger 對象,默認(rèn)的日志級別被設(shè)置為 WARNING,該函數(shù)可選的參數(shù)如下表所示。
|
參數(shù)名稱 |
參數(shù)描述 |
|---|---|
|
filename |
日志輸出到文件的文件名 |
|
filemode |
文件模式,r[+]、w[+]、a[+] |
|
format |
日志輸出的格式 |
|
datefat |
日志附帶日期時間的格式 |
|
style |
格式占位符,默認(rèn)為 "%" 和 “{}” |
|
level |
設(shè)置日志輸出級別 |
|
stream |
定義輸出流,用來初始化 StreamHandler 對象,不能 filename 參數(shù)一起使用,否則會ValueError 異常 |
|
handles |
定義處理器,用來創(chuàng)建 Handler 對象,不能和 filename 、stream 參數(shù)一起使用,否則也會拋出 ValueError 異常 |
logging代碼
logging.debug("debug")
logging.info("info")
logging.warning("warning")
logging.error("error")5 logging.critical("critical")
測試結(jié)果
WARNING:root:warning
ERROR:root:error
CRITICAL:root:critical
但是當(dāng)發(fā)生異常時,直接使用無參數(shù)的 debug() 、 info() 、 warning() 、 error() 、 critical() 方法并不能記錄異常信息,需要設(shè)置 exc_info=True 才可以,或者使用 exception() 方法,還可以使用 log() 方法,但還要設(shè)置日志級別和 exc_info 參數(shù)
a = 5
b = 0
try:
c = a / b
except Exception as e:
# 下面三種方式三選一,推薦使用第一種
logging.exception("Exception occurred")
logging.error("Exception occurred", exc_info=True)
logging.log(level=logging.ERROR, msg="Exception occurred", exc_info=True)
|4logging之Formatter對象
Formatter 對象用來設(shè)置具體的輸出格式,常用格式如下表所示
|
格式 |
變量描述 |
|---|---|
|
%(asctime)s |
將日志的時間構(gòu)造成可讀的形式,默認(rèn)情況下是精確到毫秒,如 2018-10-13 23:24:57,832,可以額外指定 datefmt 參數(shù)來指定該變量的格式 |
|
%(name) |
日志對象的名稱 |
|
%(filename)s |
不包含路徑的文件名 |
|
%(pathname)s |
包含路徑的文件名 |
|
%(funcName)s |
日志記錄所在的函數(shù)名 |
|
%(levelname)s |
日志的級別名稱 |
|
%(message)s |
具體的日志信息 |
|
%(lineno)d |
日志記錄所在的行號 |
|
%(pathname)s |
完整路徑 |
|
%(process)d |
當(dāng)前進(jìn)程ID |
|
%(processName)s |
當(dāng)前進(jìn)程名稱 |
|
%(thread)d |
當(dāng)前線程ID |
|
%threadName)s |
當(dāng)前線程名稱 |
|5logging封裝類
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
__title__ = logging工具類
__Time__ = 2019/8/8 19:26
"""
import logging
from logging import handlers
class Loggers:
__instance = None
def __new__(cls, *args, **kwargs):
if not cls.__instance:
cls.__instance = object.__new__(cls, *args, **kwargs)
return cls.__instance
def __init__(self):
# 設(shè)置輸出格式
formater = logging.Formatter(
'[%(asctime)s]-[%(levelname)s]-[%(filename)s]-[%(funcName)s:%(lineno)d] : %(message)s')
# 定義一個日志收集器
self.logger = logging.getLogger('log')
# 設(shè)定級別
self.logger.setLevel(logging.DEBUG)
# 輸出渠道一 - 文件形式
self.fileLogger = handlers.RotatingFileHandler("./test.log", maxBytes=5242880, backupCount=3)
# 輸出渠道二 - 控制臺
self.console = logging.StreamHandler()
# 控制臺輸出級別
self.console.setLevel(logging.DEBUG)
# 輸出渠道對接輸出格式
self.console.setFormatter(formater)
self.fileLogger.setFormatter(formater)
# 日志收集器對接輸出渠道
self.logger.addHandler(self.fileLogger)
self.logger.addHandler(self.console)
def debug(self, msg):
self.logger.debug(msg=msg)
def info(self, msg):
self.logger.info(msg=msg)
def warn(self, msg):
self.logger.warning(msg=msg)
def error(self, msg):
self.logger.error(msg=msg)
def excepiton(self, msg):
self.logger.exception(msg=msg)
loggers = Loggers()
if __name__ == '__main__':
loggers.debug('debug')
loggers.info('info')
|6logzero封裝類
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
__title__ = logzero日志封裝類
__Time__ = 2019/8/8 19:26
"""
import logging
import logzero
from logzero import logger
class Logzero(object):
__instance = None
def __new__(cls, *args, **kwargs):
if not cls.__instance:
cls.__instance = object.__new__(cls, *args, **kwargs)
return cls.__instance
def __init__(self):
self.logger = logger
# console控制臺輸入日志格式 - 帶顏色
self.console_format = '%(color)s' \
'[%(asctime)s]-[%(levelname)1.1s]-[%(filename)s]-[%(funcName)s:%(lineno)d] 日志信息: %(message)s ' \
'%(end_color)s '
# 創(chuàng)建一個Formatter對象
self.formatter = logzero.LogFormatter(fmt=self.console_format)
# 將formatter提供給setup_default_logger方法的formatter參數(shù)
logzero.setup_default_logger(formatter=self.formatter)
# 設(shè)置日志文件輸出格式
self.formater = logging.Formatter(
'[%(asctime)s]-[%(levelname)s]-[%(filename)s]-[%(funcName)s:%(lineno)d] 日志信息: %(message)s')
# 設(shè)置日志文件等級
logzero.loglevel(logging.DEBUG)
# 輸出日志文件路徑和格式
logzero.logfile("F:\\imocInterface\\log/tests.log", formatter=self.formater)
def debug(self, msg):
self.logger.debug(msg=msg)
def info(self, msg):
self.logger.info(msg=msg)
def warning(self, msg):
self.logger.warning(msg=msg)
def error(self, msg):
self.logger.error(msg=msg)
def exception(self, msg):
self.logger.exception(msg=msg)
logzeros = Logzero()
if __name__ == '__main__':
logzeros.debug("debug")
logzeros.info("info")
logzeros.warning("warning")
logzeros.error("error")
a = 5
b = 0
try:
c = a / b
except Exception as e:
logzeros.exception("Exception occurred")
總結(jié)
以上所述是小編給大家介紹的Python中l(wèi)ogging日志庫實例詳解,希望對大家有所幫助,也非常感謝大家對腳本之家網(wǎng)站的支持!
相關(guān)文章
pytorch中的torch.nn.Conv2d()函數(shù)圖文詳解
這篇文章主要給大家介紹了關(guān)于pytorch中torch.nn.Conv2d()函數(shù)的相關(guān)資料,文中通過實例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2022-02-02
解決mnist數(shù)據(jù)集下載的相關(guān)問題
這篇文章主要介紹了解決mnist數(shù)據(jù)集下載的相關(guān)問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-06-06
終于搞懂了Python中super(XXXX,?self).__init__()的作用了
本文主要介紹了終于搞懂了Python中super(XXXX,?self).__init__()的作用了,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-08-08
Python Numpy實現(xiàn)計算矩陣的均值和標(biāo)準(zhǔn)差詳解
NumPy(Numerical Python)是Python的一種開源的數(shù)值計算擴(kuò)展。這種工具可用來存儲和處理大型矩陣,比Python自身的嵌套列表結(jié)構(gòu)要高效的多。本文主要介紹用NumPy實現(xiàn)計算矩陣的均值和標(biāo)準(zhǔn)差,感興趣的小伙伴可以了解一下2021-11-11
Python內(nèi)置函數(shù)—vars的具體使用方法
本篇文章主要介紹了Python內(nèi)置函數(shù)—vars的具體使用方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-12-12

