环境:mac 10.12 python3 django 1.10
最近刚从arch 换到 mac下搬砖, 发如今arch跑的好好的代码,在mac下 终端总是报错 .... 仍是编码错误...html
code:python
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就出错,那多半是环境问题了,而后我就开始了个人调试追踪之旅了django
先前调试都是一晃而过,只看结果。 然并软,并无什么用,后面耐着性子单独调试app
首先从错误点开始:post
/usr/local/Cellar/python3/3.5.2_3/Frameworks/Python.framework/Versions/3.5/lib/python3.5/logging/__init__.py line: 982google
发现这里出现ASCII编码,感受拿到钥匙了~~编码
而后顺藤摸瓜,去看了 这个 stream 的初始化,发现标准的stderr 读写都是 encoding='utf-8',spa
可是读写日志文件就指定了 ASCII编码。debug
知道了缘由,就好解决了,google 一圈未果,马丹,居然百度一下就知道怎么写(应该是歪果仁都不会有这个问题吧)
在 LOGGING 的 handlers 中配置编码就好了
'debug': { 'level': 'DEBUG', 'class': 'logging.handlers.RotatingFileHandler', 'filename': 'log/debug.log', 'maxBytes': 1024 * 1024 * 5, 'backupCount': 5, 'formatter': 'standard', "encoding": "utf8" },