如何在 Python 中临时更改记录消息的格式? [英] How to change the format of logged messages temporarily, in Python?

查看:37
本文介绍了如何在 Python 中临时更改记录消息的格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Python 中临时更改日志消息格式的最简单方法是什么(通过日志模块)?

What is the simplest method for temporarily changing the logging message format, in Python (through the logging module)?

目标是拥有一些标准的消息格式,同时能够临时添加有关正在读取的某些文件的信息(如其名称);当不再读取文件时,消息格式应恢复为默认值.生成消息的程序知道正在读取什么文件,因此如果其消息自动包含相关文件名(错误消息将是:ERROR while正在读取文件 ***: ..." 而不是 "ERROR: ...").

The goal is to have some standard message format, while being able to temporarily add information about some file being read (like its name); the message format should revert to its default when the file is not being read anymore. The program that produces the messages is not aware of what file is being read, so it would be nice if its message automatically included the relevant file name (the error message would be: "ERROR while reading file ***: …" instead of "ERROR: …").

推荐答案

这里有一个简单的解决方案,可以从 推导出来Vinay Sajip 自己的HOWTO;它基本上用 setFormatter() 更新日志格式化程序:

Here is a simple solution, that can be deduced from Vinay Sajip's own HOWTO; it basically updates the logging formatter with setFormatter():

import logging

logger = logging.getLogger()  # Logger
logger_handler = logging.StreamHandler()  # Handler for the logger
logger.addHandler(logger_handler)

# First, generic formatter:
logger_handler.setFormatter(logging.Formatter('%(message)s'))
logger.error('error message')  # Test

# New formatter for the handler:
logger_handler.setFormatter(logging.Formatter('PROCESSING FILE xxx - %(message)s'))
logger.error('error message')  # Test

这正确产生:

error message
PROCESSING FILE xxx - error message

(其中 xxx 可以动态设置为正在处理的文件,如问题中所要求的那样).

(where xxx can be set dynamically to the file being processed, as asked for in the question).

这篇关于如何在 Python 中临时更改记录消息的格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆