python-logging.handlers.SMTPHandler-发送unicode内容

今天在写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内容

相关文章:

你感兴趣的文章:

标签云: