What is the simplest method for temporarily changing the logging message format, in Python (through the logging module)?
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: …”).
Here is a simple solution, that can be deduced from Vinay Sajip‘s own HOWTO; it basically updates the logging formatter with
setFormatter():This correctly produces:
(where
xxxcan be set dynamically to the file being processed, as asked for in the question).