以UTF-8格式进行Django SQL日志记录:在settings.DEBUG = True时避免UnicodeDecodeError [英] Django SQL Logging as UTF-8 : avoiding UnicodeDecodeError while settings.DEBUG=True
问题描述
很长一段时间以来,我一直在为模型进行save()时遇到"UnicodeDecodeError:ascii编解码器无法解码..."错误,直到我意外地"设置了设置.DEBUG= False.然后我意识到Unicode异常不是来自我的数据也不来自我的代码,而是来自Django的SQL日志记录,这显然是ascii.
For a long time, I've had to struggle with a "UnicodeDecodeError:ascii codec can't decode..." error while save()-ing a model, until I "accidentally" set settings.DEBUG=False. I realized then that the Unicode exception was not from my data nor from my code, but from Django's SQL logging, which is apparently in ascii.
问题是,有没有一种简单的方法可以将日志记录从ascii转换为utf-8,这样我仍然可以利用日志记录功能而无需处理异常?
Question is, is there an easy way to convert the logging from ascii to utf-8, so that I can still avail of the logging feature without dealing with the exception?
非常感谢!=)
推荐答案
我发现了目前似乎可以正常使用的hack.在django/db/backends/util.py中:
I found a hack which seems to work for the time being. In django/db/backends/util.py:
class CursorDebugWrapper(CursorWrapper):
# XXX callproc isn't instrumented at this time.
def execute(self, sql, params=None):
start = time()
try:
return super(CursorDebugWrapper, self).execute(sql, params)
finally:
stop = time()
duration = stop - start
sql = self.db.ops.last_executed_query(self.cursor, sql, params)
self.db.queries.append({
'sql': sql,
'time': "%.3f" % duration,
})
logger.debug('(%.3f) %s; args=%s' % (duration, sql, params),
extra={'duration': duration, 'sql': sql, 'params': params}
)
我将最后一行更改为:
logger.debug('(%.3f) %s; args=%s' % (duration, sql.decode('utf-8'), params),
extra={'duration': duration, 'sql': sql, 'params': params}
)
如果有人可以给出更好/更优雅的解决方案,那就太好了.
Would be great if someone could give a better / more elegant solution.
这篇关于以UTF-8格式进行Django SQL日志记录:在settings.DEBUG = True时避免UnicodeDecodeError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!