本篇內(nèi)容介紹了“python3 logging日志如何封裝”的有關(guān)知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領(lǐng)大家學習一下如何處理這些情況吧!希望大家仔細閱讀,能夠?qū)W有所成!

Python主要應用于:1、Web開發(fā);2、數(shù)據(jù)科學研究;3、網(wǎng)絡(luò)爬蟲;4、嵌入式應用開發(fā);5、游戲開發(fā);6、桌面應用開發(fā)。
一個完整的程序離不開日志,無論是開發(fā)階段,還是測試階段,亦或程序運行階段,都可以通過日志查看程序的運行情況,或是定位問題。
下面是對 python3 的日志庫 logging 進行了封裝,對于大部分的需求應該是能滿足的。(
程序結(jié)構(gòu):
|--logger.py | |--singleton.py | |--demo.py | |--log | | | 2018-10-12.log
logger.py
import os
import sys
import time
import logging
from singleton import Singleton
@Singleton # 如需打印不同路徑的日志(運行日志、審計日志),則不能使用單例模式(注釋或刪除此行)。此外,還需設(shè)定參數(shù)name。
class Logger:
def __init__(self, set_level="INFO",
name=os.path.split(os.path.splitext(sys.argv[0])[0])[-1],
log_name=time.strftime("%Y-%m-%d.log", time.localtime()),
log_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), "log"),
use_console=True):
"""
:param set_level: 日志級別["NOTSET"|"DEBUG"|"INFO"|"WARNING"|"ERROR"|"CRITICAL"],默認為INFO
:param name: 日志中打印的name,默認為運行程序的name
:param log_name: 日志文件的名字,默認為當前時間(年-月-日.log)
:param log_path: 日志文件夾的路徑,默認為logger.py同級目錄中的log文件夾
:param use_console: 是否在控制臺打印,默認為True
"""
if not set_level:
set_level = self._exec_type() # 設(shè)置set_level為None,自動獲取當前運行模式
self.__logger = logging.getLogger(name)
self.setLevel(getattr(logging, set_level.upper()) if hasattr(logging, set_level.upper()) else logging.INFO) # 設(shè)置日志級別
if not os.path.exists(log_path): # 創(chuàng)建日志目錄
os.makedirs(log_path)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
handler_list = list()
handler_list.append(logging.FileHandler(os.path.join(log_path, log_name), encoding="utf-8"))
if use_console:
handler_list.append(logging.StreamHandler())
for handler in handler_list:
handler.setFormatter(formatter)
self.addHandler(handler)
def __getattr__(self, item):
return getattr(self.logger, item)
@property
def logger(self):
return self.__logger
@logger.setter
def logger(self, func):
self.__logger = func
def _exec_type(self):
return "DEBUG" if os.environ.get("IPYTHONENABLE") else "INFO"singleton.py
class Singleton: """ 單例裝飾器。 """ __cls = dict() def __init__(self, cls): self.__key = cls def __call__(self, *args, **kwargs): if self.__key not in self.cls: self[self.__key] = self.__key(*args, **kwargs) return self[self.__key] def __setitem__(self, key, value): self.cls[key] = value def __getitem__(self, item): return self.cls[item] @property def cls(self): return self.__cls @cls.setter def cls(self, cls): self.__cls = cls
demo.py
import logger
x = logger.Logger("debug")
x.critical("這是一個 critical 級別的問題!")
x.error("這是一個 error 級別的問題!")
x.warning("這是一個 warning 級別的問題!")
x.info("這是一個 info 級別的問題!")
x.debug("這是一個 debug 級別的問題!")
x.log(50, "這是一個 critical 級別的問題的另一種寫法!")
x.log(40, "這是一個 error 級別的問題的另一種寫法!")
x.log(30, "這是一個 warning 級別的問題的另一種寫法!")
x.log(20, "這是一個 info 級別的問題的另一種寫法!")
x.log(10, "這是一個 debug 級別的問題的另一種寫法!")
x.log(51, "這是一個 Level 51 級別的問題!")
x.log(11, "這是一個 Level 11 級別的問題!")
x.log(9, "這條日志等級低于 debug,不會被打印")
x.log(0, "這條日志同樣不會被打印")
"""
運行結(jié)果:
2018-10-12 00:18:06,562 - demo - CRITICAL - 這是一個 critical 級別的問題!
2018-10-12 00:18:06,562 - demo - ERROR - 這是一個 error 級別的問題!
2018-10-12 00:18:06,562 - demo - WARNING - 這是一個 warning 級別的問題!
2018-10-12 00:18:06,562 - demo - INFO - 這是一個 info 級別的問題!
2018-10-12 00:18:06,562 - demo - DEBUG - 這是一個 debug 級別的問題!
2018-10-12 00:18:06,562 - demo - CRITICAL - 這是一個 critical 級別的問題的另一種寫法!
2018-10-12 00:18:06,562 - demo - ERROR - 這是一個 error 級別的問題的另一種寫法!
2018-10-12 00:18:06,562 - demo - WARNING - 這是一個 warning 級別的問題的另一種寫法!
2018-10-12 00:18:06,562 - demo - INFO - 這是一個 info 級別的問題的另一種寫法!
2018-10-12 00:18:06,562 - demo - DEBUG - 這是一個 debug 級別的問題的另一種寫法!
2018-10-12 00:18:06,562 - demo - Level 51 - 這是一個 Level 51 級別的問題!
2018-10-12 00:18:06,562 - demo - Level 11 - 這是一個 Level 11 級別的問題!
"""
2018-10-12.log
2018-10-12 00:18:06,562 - demo - CRITICAL - 這是一個 critical 級別的問題!
2018-10-12 00:18:06,562 - demo - ERROR - 這是一個 error 級別的問題!
2018-10-12 00:18:06,562 - demo - WARNING - 這是一個 warning 級別的問題!
2018-10-12 00:18:06,562 - demo - INFO - 這是一個 info 級別的問題!
2018-10-12 00:18:06,562 - demo - DEBUG - 這是一個 debug 級別的問題!
2018-10-12 00:18:06,562 - demo - CRITICAL - 這是一個 critical 級別的問題的另一種寫法!
2018-10-12 00:18:06,562 - demo - ERROR - 這是一個 error 級別的問題的另一種寫法!
2018-10-12 00:18:06,562 - demo - WARNING - 這是一個 warning 級別的問題的另一種寫法!
2018-10-12 00:18:06,562 - demo - INFO - 這是一個 info 級別的問題的另一種寫法!
2018-10-12 00:18:06,562 - demo - DEBUG - 這是一個 debug 級別的問題的另一種寫法!
2018-10-12 00:18:06,562 - demo - Level 51 - 這是一個 Level 51 級別的問題!
2018-10-12 00:18:06,562 - demo - Level 11 - 這是一個 Level 11 級別的問題!“python3 logging日志如何封裝”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識可以關(guān)注創(chuàng)新互聯(lián)網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實用文章!
當前名稱:python3logging日志如何封裝-創(chuàng)新互聯(lián)
文章網(wǎng)址:http://chinadenli.net/article8/dgpdip.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供Google、微信公眾號、自適應網(wǎng)站、搜索引擎優(yōu)化、軟件開發(fā)、定制網(wǎng)站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容