Question to logging

Vinay Sajip at Red Dove vinay_sajip at red-dove.com
Wed Dec 16 18:31:03 CET 2009


On 16/12/2009 12:49, stefan.messerli.1 at postfinance.ch wrote:
> I have the following error and no clue, how to solve that. Up to python version 2.5 the following script worked without an error, but since python 2.6. I get the following error:
>
> #!/usr/bin/env python
> # -*- coding: ISO-8859-1 -*-
> import logging
> logging.getLogger().addHandler( logging.StreamHandler() )
> log = logging.getLogger()
> t = "äöü"
> print "this is printed   : " + t
> log.error( "this is log.error : " + t )
>
>
>
> # running the above script with Python 2.5
> $ ./x.py
> this is printed   : äöü
> this is log.error : äöü
>
>
> # running the above script with Python 2.6
> $ ./x.py
> this is printed   : äöü
> Traceback (most recent call last):
>   File "/var/tmp/pf-python-2.6-2.6.1-root/appl_local/python-2.6/lib/python2.6/logging/__init__.py", line 765, in emit
> UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 20: ordinal not in range(128)
>
>
> I found your answer of issue6991 in bugs.python.org, where somebody had a similar problem, but to be honest, I have no idea how to solve my problem.
>
> Can you please give me a tip what I have to change or where I can find more information ?
>   

Hello Stefan,

You should pass a stream to StreamHandler which has an encoding
attribute set to the appropriate encoding (presumably iso-8859-1) and
ensure that your stream will encode any Unicode sent to it with that
encoding. For example,

import codecs
ENCODING = 'iso-8859-1' # or whatever
writer = codecs.getwriter(ENCODING)
w = writer(sys.stderr)
w.encoding = ENCODING
...
handler = logging.StreamHandler(w)
...

In future, please ask questions like this on comp.lang.python
(python-list at python.org) to give others the chance to participate in any
discussion.

Regards,

Vinay Sajip





More information about the Python-list mailing list