[Django]-Django UnicodeEncodeError when logging sql with unicode from BinaryField

4👍

Setting the encoding of the log handler to utf-8 seems to work. If there’s a better way please advise.

LOGGING = {
    # other config omitted
    'handlers': {
        'django-debug': {
            'level': 'DEBUG',
            'class':'logging.FileHandler',
            'filename': os.path.join(LOCAL_LOGGING_PATH,'django-debug.log'),
            'formatter': 'standard',
            'encoding':'utf8', # this fixes UnicodeEncodeError
        }
    }
}

Things I tried that didn’t work. These all still produce UnicodeEncodeError:

  • Add from __future__ import unicode_literals at the top of settings.py

  • Add the Byte Order Mark (BOM) character \ufeff to the formatter as suggested by the python 3 logging cookbook

  • Use %r instead of %s in the log formatter

  • Use the python unicode string on the formatter 'format': u'%(asctime)-s %(levelname)s [%(name)s]: %(message)s', and then logging._defaultFormatter = logging.Formatter(u"%(message)s") as suggested in this thread

👤jd80

Leave a comment