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: …").
I don't recommend this; but you can say assume the first root handler is the one that's screwed up and modify it directly
if you are in any system with managed logging; this is probably going to shoot your foot; it really would be best to be able to determine an exact reference to the handler you want to modify and modify that;
but nobody cares how broken it is if it works right?/s
There are several ways. Apart from the already documented ones (
extra
argument to logging calls,LoggerAdapter
,Filter
) , another way would be to specify a custom formatting class, whose instance you can keep informed about the file being processed. For example:Instantiate the formatter ...
Process files ...
This is very simplistic - for example, not for use in threaded environments if file processing is done by different threads concurrently.
Update: Although the root logger's handlers are accessible via
logging.getLogger().handlers
, this is an implementation detail that could change. As your requirement is not that basic, you could perhaps usedictConfig()
to configure your logging (available via the logutils project for older versions of Python).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
xxx
can be set dynamically to the file being processed, as asked for in the question).