我正在努力将logging所有日志记录转换为库,但我已经在这一步上停留了一段时间。我通常使用一些颜色代码转义序列登录到控制台以进行格式化。这在控制台中运行良好,但在日志文件中不起作用,日志文件不应该有任何转义序列。因此,我有一个修剪转义序列的函数。但是,我不知道如何将该函数链接到我用于控制台输出的格式化程序。这是我用于日志记录设置的内容: file_formatter = new_logging.Formatter(log_file_format) file_handler = logging.FileHandler(output_path) file_handler.setLevel(logging.DEBUG) file_handler.setFormatter(file_formatter) logging.getLogger().addHandler(file_handler) console_formatter = logging.Formatter(log_console_format) console_handler = logging.StreamHandler() console_handler.setLevel(logging.INFO) console_handler.setFormatter(console_formatter) logging.getLogger().addHandler(console_handler)本质上,我的目标是自动运行一个函数remove_escape_sequences(log_string)作为file_formatter. 现在它只是设置为一个带有占位符的字符串,'%(asctime)s %(levelname)8s: "%(name)24s" - %(message)s'. 我怎样才能做到这一点?
1 回答
翻阅古今
TA贡献1780条经验 获得超5个赞
最后自己找到了答案:
您可以Formatter通过创建一个子类来将自定义处理函数实现到 a 中,在该子类中您可以format使用自定义方法覆盖基本方法。在以下实现中,format将首先调用基本方法,然后在返回值上调用自定义函数:
class CustomFormatter(logging.Formatter):
def format(self, record):
default_formatted = logging.Formatter.format(self, record)
return custom_processing_method(default_formatted)
这个自定义格式化程序可以与标准格式化程序完全相同,包括初始化和附加。
添加回答
举报
0/150
提交
取消