Django logging 报中文编码错误
2017-12-05 本文已影响0人
Sunnky
在打印日志的时候错误如下:
--- Logging error ---
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/logging/__init__.py", line 982, in emit
stream.write(msg)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 288-294: ordinal not in range(128)
python3环境下,按理说应该不出现中文编码错误,但如果没有指定文件流的编码,有时候就会出现这个错误,所以在日志配置中要加上写入流的编码:
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'standard': {
'format': '%(levelname)s %(asctime)s %(module)s %(message)s'
},
},
'filters': {
},
'handlers': {
'console': {
'level': 'INFO',
'class': 'logging.StreamHandler',
'formatter': 'standard'
},
'mail_admins': {
'level': 'ERROR',
'class': 'django.utils.log.AdminEmailHandler',
'formatter': 'standard',
},
'debug': {
'level': 'INFO',
'class': 'logging.handlers.TimedRotatingFileHandler',
'filename': './log/debug.log',
'when': 'D',
'backupCount': 20,
'encoding': 'utf8',
'formatter': 'standard',
},
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': False
},
'debug': {
'handlers': ['console', 'debug'],
'level': 'INFO',
'propagate': True
},
}
}
其中'encoding': 'utf8',
,就是指定了编码为utf-8