Python类实例化问题:Froggius日志库日志输出异常
问题解决与代码改造方案
核心问题分析
- 实例方法缺少
self参数:Python实例方法的第一个参数必须是实例本身(惯例命名为self),你的debug方法没有该参数,导致调用instance.debug('Hello World')时,log_msg实际接收的是Froggius实例对象,因此日志输出了实例的字符串表示。 - 全局变量导致实例配置冲突:使用
glob_file_path和glob_print_out全局变量存储配置,多个实例会共享同一份配置,违背了实例化后各实例独立配置的预期。
修改后的完整代码
from datetime import datetime class Froggius(): """ Main class of Froggius Includes logging methods """ def __init__(self, file_path=None, print_out=True) -> None: # 用实例属性替代全局变量,每个实例拥有独立配置 self.file_path = file_path # 初始化默认开启控制台输出,与文档描述一致 self.print_out = print_out def debug(self, log_msg, file_path=None, print_out=None, highlighting=True): """ Writes logs, optionally to a file. Parameters ---------- log_msg : str The message to be logged. file_path : str, optional The path to the file where the log should be saved, by default None highlighting : bool, optional Whether the DEBUG tag should be highlighted with ANSI escape sequences, by default True print_out : bool, optional Whether the log should be printed to the stdout, by default True """ # 优先使用方法传入的参数,无则回退到实例初始化配置 target_file = file_path if file_path is not None else self.file_path target_print = print_out if print_out is not None else self.print_out # 生成带时间戳的日志内容 timestamp = datetime.now().strftime("%d/%m/%Y %H:%M:%S") # 处理高亮逻辑 tag = "[DBG]" if highlighting: tag = "\033[94m[DBG]\033[0m" # 蓝色高亮DBG标签 log_str = f"{tag} [{timestamp}] {log_msg}" # 控制台输出 if target_print: print(log_str) # 文件写入(移除ANSI转义符避免乱码) if target_file: plain_log_str = log_str.replace("\033[94m", "").replace("\033[0m", "") with open(target_file, 'a', encoding='utf-8') as f: f.write(plain_log_str + '\n')
关键修改点说明
- 添加
self参数:给debug及其他日志方法(如warning)都加上self作为第一个参数,确保实例方法能正确接收实例对象,避免参数传递错位。 - 替换全局变量为实例属性:用
self.file_path和self.print_out存储每个实例的配置,不同实例的配置互不干扰。 - 参数优先级逻辑:调用日志方法时,若传入
file_path或print_out则优先使用临时参数,否则使用实例初始化时的配置,兼顾灵活性与默认配置。 - 补全高亮逻辑:根据文档中的
highlighting参数,添加ANSI转义符实现控制台高亮,同时写入文件时自动移除转义符避免乱码。
验证调用
运行预期代码:
from froggius import Froggius instance = Froggius() instance.debug('Hello World')
会输出正常日志内容:
[DBG] [03/04/2024 15:16:15] Hello World
(开启高亮时,[DBG]会显示为蓝色)
内容的提问来源于stack exchange,提问作者zlElo
相关产品推荐
相关产品推荐

