[openstack-dev] [oslo] Logging exceptions and Python 3

Johannes Erdfelt johannes at erdfelt.com
Fri May 16 13:11:00 UTC 2014


On Thu, May 15, 2014, Victor Stinner <victor.stinner at enovance.com> wrote:
> I'm trying to define some rules to port OpenStack code to Python 3. I just 
> added a section in the "Port Python 2 code to Python 3" about formatting 
> exceptions and the logging module:
> https://wiki.openstack.org/wiki/Python3#logging_module_and_format_exceptions
> 
> The problem is that I don't know what is the best syntax to log exceptions. 
> Some projects convert the exception to Unicode, others use str(). I also saw 
> six.u(str(exc)) which is wrong IMO (it can raise unicode error if the message 
> contains a non-ASCII character).
> 
> IMO the safest option is to use str(exc). For example, use 
> LOG.debug(str(exc)).
> 
> Is there a reason to log the exception as Unicode on Python 2?

Because the exception uses unicode characters?

This isn't common, but it does happen and a lot of code in nova uses
unicode(exc) as a result.

Using str(exc) is bad because it will fail with any exception with
unicode characters.

six.u(exc) is bad too since it's only for text literals. It's mostly
obsolete too since Python 3.3 has the u prefix again and I don't think
any OpenStack projects target 3.0->3.2

six.text_type(exc) is the recommended solution.

JE




More information about the OpenStack-dev mailing list