Python自定義logger模塊的實例代碼
1. 內置logger
Python標準庫中的logging模塊提供了日志記錄的功能
允許開發(fā)者通過創(chuàng)建日志記錄器、處理程序和格式化器來控制日志的生成和輸出
以下是logging模塊的一些主要組件和概念:
- 日志記錄器 (Logger):整個日志系統(tǒng)的主要入口點
每個日志記錄操作都通過一個特定的日志記錄器來執(zhí)行。通常,每個模塊或子系統(tǒng)都會創(chuàng)建自己的日志記錄器
使用logging.getLogger(name)
方法來獲取或創(chuàng)建一個日志記錄器,其中name參數是日志記錄器的名稱。如果省略name參數,則返回根日志記錄器 - 處理程序 (Handler):
負責將日志記錄發(fā)送到指定的目標,比如控制臺、文件、網絡等
通過logging.StreamHandler
、logging.FileHandler
等類來創(chuàng)建不同類型的處理程序 - 格式化器 (Formatter):定義了日志消息的外觀
通過指定格式字符串來自定義日志消息的格式 或者 使用logging.Formatter
類創(chuàng)建格式化器 - 日志級別 (Log Level):
日志級別用于表示日志消息的重要性或嚴重程度,按嚴重程度從低到高排序:DEBUG、INFO、WARNING、ERROR、CRITICAL
日志記錄器和處理程序可以設置最小日志級別,只有達到或超過該級別的日志消息才會被處理
import logging # 創(chuàng)建日志記錄器 logger = logging.getLogger('碼農研究僧') logger.setLevel(logging.DEBUG) # 創(chuàng)建處理程序并設置級別 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')
截圖如下:
如果日志記錄器設置的登記為WARNING
# 創(chuàng)建日志記錄器 logger = logging.getLogger('碼農研究僧') logger.setLevel(logging.WARNING)
則輸出結果如下:
2. 自定義logger
自定義 Logger 可以根據項目的需求定制化日志記錄,滿足特定的日志記錄格式、輸出目標和日志級別等要求
通過自定義 Logger,可以實現以下功能:
- 定制化日志格式:可以根據需求定義日志的格式,包括時間、模塊、級別、消息等信息
- 輸出到不同的目標:可以將日志記錄到控制臺、文件、數據庫、網絡等不同的目標,方便日志的查看和管理
- 靈活設置日志級別:可以根據項目的需要設置不同級別的日志記錄,滿足不同的調試和排錯需求
- 增加額外的功能:可以擴展 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 級別的日志,并附帶額外的參數和關鍵字參數 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模塊的實例代碼的詳細內容,更多關于Python自定義logger模塊的資料請關注腳本之家其它相關文章!
相關文章
python使用paramiko模塊通過ssh2協(xié)議對交換機進行配置的方法
今天小編就為大家分享一篇python使用paramiko模塊通過ssh2協(xié)議對交換機進行配置的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-07-07Python利用multiprocessing實現最簡單的分布式作業(yè)調度系統(tǒng)實例
這篇文章主要給大家介紹了關于Python利用multiprocessing如何實現最簡單的分布式作業(yè)調度系統(tǒng)的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面來一起看看吧。2017-11-11