четверг, 27 ноября 2008 г.

UnicodeEncodeError in Python logging

I use Python logging facility to write my logs via syslog. But when trying to log some Unicode message, emit method somewhere deep in logging throws UnicodeEncodeError. This happens because it tries to send Unicode string to a socket.

I googled it around and found no solution. File handlers support encoding parameters, but others do not.

The simplest way I found to fix this is to use custom formatter:

from logging import Formatter

class Utf8LogFormatter(Formatter):
def format(self, record):
return Formatter.format(self, record).encode('utf8')

Is this a Python logging system problem or am I doing something wrong?

Комментариев нет: