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

Doug Hellmann doug.hellmann at dreamhost.com
Wed May 21 15:38:44 UTC 2014


On Thu, May 15, 2014 at 11:29 AM, Victor Stinner
<victor.stinner at enovance.com> wrote:
> Hi,
>
> 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?

Exception classes that define translatable strings may end up with
unicode characters that can't be converted to the default encoding
when str() is called. It's better to let the logging code handle the
conversion from an exception object to a string, since the logging
code knows how to deal with unicode properly.

So, write:

    LOG.debug(u'Could not do whatever you asked: %s', exc)

or just:

    LOG.debug(exc)

instead of converting explicitly.

Doug

>
> Victor
>
> _______________________________________________
> OpenStack-dev mailing list
> OpenStack-dev at lists.openstack.org
> http://lists.openstack.org/cgi-bin/mailman/listinfo/openstack-dev



More information about the OpenStack-dev mailing list