E pur si muove

Warnings revisited (aka logging vs warnings)

Wednesday, November 22, 2006

Earlier I posted about how to make warning messages from warnings.warn() look like fairly normal messages so they don't give you all the details about which line of code called them. The result was neat, but I found it a fairly crude way of doing it.

There is another module that does something very similar for getting messages to the user, and even slightly more flexible, and it is called logging. Don't be deceived by it's name like I was, it can be used to just "log" onto the console too. It's even better as the default behaviour is very close to what a console application would need. Let me show the code to get this going:

import logging logging.basicConfig(format='%(levelname)s: %(message)s') logging.warn("Foo is warnging you about bar")

That's it, and it is a lot cleaner then doing this using the warnings module.

Leaves the question, which module to chose. I was wondering too, and a search on "warnings vs logging" only gives one real result. Luckily the explenation of Kristian Reis agrees with what my gut feeling has started to suppose:

warnings are for code `issues', log messages are for application level `issues', right?

I didn't find anyone answering that question, but at least I agree with it. So I reckon it is right...

Wednesday, November 22, 2006 | Labels: |


Stephen Thorne said...

The warnings module is wonderful because it can tell you the calling context that actually caused the warning to be emitted. Perfect for code 'issues'.

The logging module only recognises a 'warning' as being a level of severity between INFO and ERROR.

$ cat
import warnings

def foo(bar):
if isinstance(bar, str):
warnings.warn('foo() called with deprecated string arg', stacklevel=2)

def baz():


$ python UserWarning: foo() called with deprecated string arg

New comments are not allowed.

Subscribe to: Post Comments (Atom)