Python自定義logger模塊的實例代碼
1. 內(nèi)置logger
Python標(biāo)準(zhǔn)庫中的logging模塊提供了日志記錄的功能
允許開發(fā)者通過創(chuàng)建日志記錄器、處理程序和格式化器來控制日志的生成和輸出
以下是logging模塊的一些主要組件和概念:
- 日志記錄器 (Logger):整個日志系統(tǒng)的主要入口點
每個日志記錄操作都通過一個特定的日志記錄器來執(zhí)行。通常,每個模塊或子系統(tǒng)都會創(chuàng)建自己的日志記錄器
使用logging.getLogger(name)
方法來獲取或創(chuàng)建一個日志記錄器,其中name參數(shù)是日志記錄器的名稱。如果省略name參數(shù),則返回根日志記錄器 - 處理程序 (Handler):
負(fù)責(zé)將日志記錄發(fā)送到指定的目標(biāo),比如控制臺、文件、網(wǎng)絡(luò)等
通過logging.StreamHandler
、logging.FileHandler
等類來創(chuàng)建不同類型的處理程序 - 格式化器 (Formatter):定義了日志消息的外觀
通過指定格式字符串來自定義日志消息的格式 或者 使用logging.Formatter
類創(chuàng)建格式化器 - 日志級別 (Log Level):
日志級別用于表示日志消息的重要性或嚴(yán)重程度,按嚴(yán)重程度從低到高排序:DEBUG、INFO、WARNING、ERROR、CRITICAL
日志記錄器和處理程序可以設(shè)置最小日志級別,只有達(dá)到或超過該級別的日志消息才會被處理
import logging # 創(chuàng)建日志記錄器 logger = logging.getLogger('碼農(nóng)研究僧') logger.setLevel(logging.DEBUG) # 創(chuàng)建處理程序并設(shè)置級別 console_handler = logging.StreamHandler() console_handler.setLevel(logging.DEBUG) # 創(chuàng)建格式化器 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') console_handler.setFormatter(formatter) # 將處理程序添加到日志記錄器 logger.addHandler(console_handler) # 記錄日志 logger.debug('This is a debug message') logger.info('This is an info message') logger.warning('This is a warning message') logger.error('This is an error message') logger.critical('This is a critical message')
截圖如下:
如果日志記錄器設(shè)置的登記為WARNING
# 創(chuàng)建日志記錄器 logger = logging.getLogger('碼農(nóng)研究僧') logger.setLevel(logging.WARNING)
則輸出結(jié)果如下:
2. 自定義logger
自定義 Logger 可以根據(jù)項目的需求定制化日志記錄,滿足特定的日志記錄格式、輸出目標(biāo)和日志級別等要求
通過自定義 Logger,可以實現(xiàn)以下功能:
- 定制化日志格式:可以根據(jù)需求定義日志的格式,包括時間、模塊、級別、消息等信息
- 輸出到不同的目標(biāo):可以將日志記錄到控制臺、文件、數(shù)據(jù)庫、網(wǎng)絡(luò)等不同的目標(biāo),方便日志的查看和管理
- 靈活設(shè)置日志級別:可以根據(jù)項目的需要設(shè)置不同級別的日志記錄,滿足不同的調(diào)試和排錯需求
- 增加額外的功能:可以擴(kuò)展 Logger 的功能,如添加日志的歸檔、壓縮、加密等功能
可以整個拷貝的logger模塊:
from datetime import datetime from os import path from sys import stdout from loguru import logger class MyLogger(object): def __init__(self, log_name, level="INFO") -> logger: logger.remove() fmt = '<level>{time:YYYY-MM-DD HH:mm:ss} | {module}: {level} >> {message}</level>' logger.add(stdout, format=fmt) self.my_logger = logger _today = datetime.today().strftime("%Y_%m_%d") log_path = f"{log_name}{_today}.log" self.name = path.basename(log_path) self.my_logger.add( log_path, encoding="utf-8", retention='7 days', rotation="50 MB", compression='zip', format=fmt, enqueue=True, level=level) def info(self, content): self.my_logger.opt(depth=1).info(content) def debug(self, content): self.my_logger.opt(depth=1).debug(content) def error(self, content, *args, **kwargs): self.my_logger.opt(depth=1).error(content) if len(args) > 0 or len(kwargs) > 0: self.exception("Error details:", *args, **kwargs) def exception(self, content, *args, **kwargs): self.my_logger.opt(depth=1).exception(content, *args, **kwargs) def warning(self, content): self.my_logger.opt(depth=1).warning(content)
測試如下:
# 創(chuàng)建一個名為 "my_app" 的日志記錄器,級別為 INFO logger = MyLogger("my_app") # 記錄一條 INFO 級別的日志 logger.info("This is an informational message.") # 記錄一條 DEBUG 級別的日志 logger.debug("This is a debug message.") # 記錄一條 ERROR 級別的日志 logger.error("This is an error message.") # 記錄一條 WARNING 級別的日志 logger.warning("This is a warning message.") # 記錄一條 ERROR 級別的日志,并附帶額外的參數(shù)和關(guān)鍵字參數(shù) logger.error("An error occurred.", "Extra info", custom_param="Custom value") # 記錄一條 ERROR 級別的日志,同時記錄異常信息 try: result = 1 / 0 except Exception as e: logger.exception("An error occurred while performing a calculation.")
截圖如下:
整體logger文件如下:
以上就是Python自定義logger模塊的實例代碼的詳細(xì)內(nèi)容,更多關(guān)于Python自定義logger模塊的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
python使用paramiko模塊通過ssh2協(xié)議對交換機(jī)進(jìn)行配置的方法
今天小編就為大家分享一篇python使用paramiko模塊通過ssh2協(xié)議對交換機(jī)進(jìn)行配置的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-07-07PyTorch 隨機(jī)數(shù)生成占用 CPU 過高的解決方法
今天小編就為大家分享一篇PyTorch 隨機(jī)數(shù)生成占用 CPU 過高的解決方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-01-01Python利用multiprocessing實現(xiàn)最簡單的分布式作業(yè)調(diào)度系統(tǒng)實例
這篇文章主要給大家介紹了關(guān)于Python利用multiprocessing如何實現(xiàn)最簡單的分布式作業(yè)調(diào)度系統(tǒng)的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起看看吧。2017-11-11