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

查看:112
本文介绍了如何在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天全站免登陆