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

Igor Kalnitsky ikalnitsky at mirantis.com
Thu May 15 21:20:21 UTC 2014


Hi,

> Is there a reason to log the exception as Unicode on Python 2?

Sure, why not? Some exceptions may have unicode message with non-ASCII
characters. and we obviously can't cast such exceptions with str() in
Python 2.x.


> The problem is that I don't know what is the best syntax to log
exceptions.

I hate this unicode dances too, since I don't understand all nuances and
potential pitfalls. But I belive the better approach is to use unicode()
for Python 2.x and str() for Python 3.x.

Example:

    LOG.error(six.text_type(e))


P.S: I've a quick look over logging implementaion, and figured out
that it has some code to dial with unicode. In few words, if we know
about exception's attributes, it's better to use it directly to log:

Example:

    LOG.error(e.message)


- Igor


On Thu, May 15, 2014 at 6:29 PM, 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?
>
> Victor
>
> _______________________________________________
> OpenStack-dev mailing list
> OpenStack-dev at lists.openstack.org
> http://lists.openstack.org/cgi-bin/mailman/listinfo/openstack-dev
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.openstack.org/pipermail/openstack-dev/attachments/20140516/4fc4cc1b/attachment.html>


More information about the OpenStack-dev mailing list