tags:

views:

26

answers:

2

Long story short:

# this works as expected:
logging.error(my_object.__unicode__())

# this doesn't:
logging.error(my_object)

Same result with __str__(self). Why?

EDIT: __str__ actually works.

+1  A: 
>>> class MyClass(object):
...     def __str__(self):
...         return "foobar"
...
>>> import logging
>>> logging.error(MyClass())
ERROR:root:foobar

Works as expected?!

Ferdinand Beyer
Turns out it actually works.
alex
+1  A: 

Logging will call str() (which uses __str__() which falls back to __repr__() when it's not defined). This is because the logging framework is not Unicode safe (i.e. you can get errors when you try to write Unicode to the various logging sinks).

Aaron Digulla
Not true. Logging will format the message using `str(msg) % args`. In Python 2.x, you should always implement both `__str__()` and `__unicode__` if you want to provide stringify-behavior.
Ferdinand Beyer