今天在写logging的时候发现 SMTPHandler不能发送unicode编码的logging, 会抛UnicodeError
在网上查了下, 这个问题也确实困扰了好多人 这个函数本身也没有提供编码的接口 查了一下相关的解决方案 在这里记录下:
import logging, logging.handlersclass EncodingFormatter(logging.Formatter): def __init__(self, fmt, datefmt=None, encoding=None): logging.Formatter.__init__(self, fmt, datefmt) self.encoding = encoding def format(self, record): result = logging.Formatter.format(self, record) if isinstance(result, unicode): result = result.encode(self.encoding or 'utf-8') return resultdef main(): root = logging.getLogger() sh = logging.handlers.SMTPHandler(mailhost=('localhost', 25), fromaddr='vms@test.com', toaddrs='test@test.com', subject='Logged Event') root.addHandler(sh) sh.setFormatter(EncodingFormatter('%(message)s', encoding='uft-8')) root.error(u'accentu\u00e9')if __name__ == '__main__': main()
原文地址:python-logging.handlers.SMTPHandler-发送unicode内容, 感谢原作者分享。 然后继续努力,把让自己跌倒的石头搬掉或绕过去,不就解决问题了吗