環境: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" },