python3 logging 'ascii' codec can't encode characters

环境:mac 10.12  python3  django 1.10

问题发现

最近刚从arch 换到 mac下搬砖, 发现在arch跑的好好的代码,在mac下 终端老是报错 .... 还是编码错误...

code:

try:
    int('sdfasdf')
except Exception as e:
    logger.error( (u' 注册失败 ' + str(e)) )
    return render(request, 'user/register.html')
        

error:

--- Logging error ---
Traceback (most recent call last):
  File "../repository/apps/user/views.py", line 104, in post
    int('sdfasdf')
ValueError: invalid literal for int() with base 10: 'sdfasdf'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/local/Cellar/python3/3.5.2_3/Frameworks/Python.framework/Versions/3.5/lib/python3.5/logging/__init__.py", line 983, in emit
    stream.write(msg)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 91-94: ordinal not in range(128)   

坦白说,看到这个错误好无奈。既然能在Linux跑,换到mac就出错,那多半是环境问题了,然后我就开始了我的调试追踪之旅了

跟踪调试

先前调试都是一晃而过,只看结果。 然并软,并没有什么用,后面耐着性子单独调试

首先从错误点开始:

/usr/local/Cellar/python3/3.5.2_3/Frameworks/Python.framework/Versions/3.5/lib/python3.5/logging/__init__.py line: 982

图片描述

发现这里出现ASCII编码,感觉拿到钥匙了~~

然后顺藤摸瓜,去看了 这个 stream 的初始化,发现标准的stderr 读写都是 encoding='utf-8',

但是读写日志文件就指定了 ASCII编码。

解决

知道了原因,就好解决了,google 一圈未果,马丹,竟然百度一下就知道怎么写(应该是歪果仁都不会有这个问题吧)

在 LOGGING 的 handlers 中配置编码就行了

    'debug': {
        'level': 'DEBUG',
        'class': 'logging.handlers.RotatingFileHandler',
        'filename': 'log/debug.log',
        'maxBytes': 1024 * 1024 * 5,
        'backupCount': 5,
        'formatter': 'standard',
        "encoding": "utf8"
    },

参考链接:每个 Python 程序员都要知道的日志实践

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值