我想使用Python的日誌包將UTF-8編碼的字符串記錄到文件中。作爲一個玩具的例子:UTF-8在Python日誌中,怎麼樣?
import logging
def logging_test():
handler = logging.FileHandler("/home/ted/logfile.txt", "w",
encoding = "UTF-8")
formatter = logging.Formatter("%(message)s")
handler.setFormatter(formatter)
root_logger = logging.getLogger()
root_logger.addHandler(handler)
root_logger.setLevel(logging.INFO)
# This is an o with a hat on it.
byte_string = '\xc3\xb4'
unicode_string = unicode("\xc3\xb4", "utf-8")
print "printed unicode object: %s" % unicode_string
# Explode
root_logger.info(unicode_string)
if __name__ == "__main__":
logging_test()
這將在logging.info()調用中使用UnicodeDecodeError爆炸。
在較低的級別上,Python的日誌包使用編解碼器包打開日誌文件,並以「UTF-8」參數作爲編碼傳入。這一切都很好,但它試圖將字節字符串寫入文件而不是unicode對象,該對象會爆炸。從本質上講,Python是這樣做的:
file_handler.write(unicode_string.encode("UTF-8"))
當它應該是這樣:
file_handler.write(unicode_string)
這是Python中的錯誤,還是我瘋服用藥片? FWIW,這是一個股票Python 2.6安裝。
您的代碼工作完全正常這裏。我努力讓它失敗,但我沒有成功。 – 2009-10-09 18:33:45
你說的對,python使用UTF-8對它進行編碼,因爲它詢問outfile使用什麼編碼,並且你指定了UTF-8,所以這一切都很好。 – 2009-10-09 18:37:11
我不得不打回來的機器找到[示例](http://web.archive.org/web/20100107060919/http://tony.czechit.net/2009/02/unicode-support-for-python -logging-library /)你提到的。有趣。 – Epu 2013-04-12 18:41:14