I have some code that's schematically along the lines of:
from logging import warning
def complex_function():
# Do some stuff
raise Warning("blah")
# Do some more stuff
raise Warning("Blah again")
try:
complex_function()
except Warning as e:
warning(e)
This results in:
WARNING:root:blah
I would like to catch all warnings raised, and log them. In my code, such warnings sometimes come from 3rd party libraries, so it is not practical to modify the warnings in place to use logging.warning
, and I also want to store the warning information so that I can return some version of that information via an API.
Is there a way for me to do something like this that catches all warnings, and loops over them?
edit
Too late, I'm realising that I'm raising warnings wrong in the example above, and complex_function
should be something long the lines of:
def complex_function():
# Do some stuff
warnings.warn("blah")
# Do some more stuff
warnings.warn("Blah again", UnknownWarningType)
And I think I can catch these with warnings.catch_warnings