使用 UTF-8 编码的 python 日志信息



我使用request.get函数在互联网上获取搜索结果。我试图将其记录在日志中。但我不知道为什么它没有显示编码字符串

export=request.get(url="https://trains.ctrip.com/pages/booking/getTransferList",params=data,headers=headers)
logging.basicConfig(filename=rb"C:StudyOtherSelf-studyCodenewfile.log", 
format='%(asctime)s %(message)s', 
filemode='wb')
handler = logging.FileHandler(rb"C:StudyOtherSelf-studyCodenewfile.log", 'wb') 
logger=logging.getLogger()
logger.setLevel(logging.DEBUG)
logger.addHandler(handler)
logging.info(export.content)

这是输出的一部分

"transferList":[{"departStation":"xe4xb8x8axe6xb5xb7xe8x99xb9xe6xa1xa5","arriveStation":"xe5x

但是当我使用 json 编写它时

f=open("C:StudyOtherSelf-studyCodeexport.json","wb")
f.write(export.content)
f.close

我得到了正确的输出

"transferList":[{"departStation":"上海虹桥","arriveStation":"南昌西",

我知道导出是一个响应类,而 export.content 是二进制的,我尝试了二进制写入或使用UTF_8编码写入,但两者都得到了相同的错误输出。在这种情况下,我可以获得正确的日志吗?

正如 Chris 在这个答案中所描述的,看起来你需要告诉处理程序将事物编码为 UTF-8。这是通过将encoding='utf-8'传递给 FileHandler(( 创建来完成的。我还没有测试过这个,但它应该工作似乎是合乎逻辑的。

最新更新