[英]Logging: How to set the newline character of log files?
我在Windows和Linux上使用Python 3.7+ 登錄,但行尾取決於平台。
雖然您可以在讀取或寫入文件時設置換行符,但顯然在設置logging.FileHandler
時不能:
https://docs.python.org/3/library/logging.handlers.html#filehandler
像logging.FileHandler(newline = '\\n')
會做,如io.open(newline = '\\n')
:
https://docs.python.org/3/library/io.html?highlight=file#io.open (讀取或寫入文件)
https://docs.python.org/3/library/io.html?highlight=file#io.TextIOWrapper (此處解釋newline
)
也許有一種方法可以確保在Windows和Linux上登錄時以相同的行結尾,但我還沒有找到。
問候。
logging.FileHandler
繼承自具有terminator
屬性的logging.StreamHandler
。 您可以在實例上設置它。 我提供了一個使用os
模塊的便攜式解決方案,但如果需要,您可以明確設置它。
import logging
h = logging.FileHandler("foo.log")
h.terminator = "\n"
編輯:固定解決方案始終使用\\n
作為行終止符。
https://docs.python.org/3/library/logging.handlers.html#logging.StreamHandler.terminator
不幸的是,您無法控制它,因為 FileHandler 在后台使用的open()
用操作系統默認值替換了換行符。 如果您真的想要對它進行特定控制,要創建與當前操作系統默認值不同的換行符,您必須子類化 FileHandler:
import logging
class MyFileHandler(logging.FileHandler):
def _open(self):
return open(self.baseFilename, self.mode, encoding=self.encoding, newline='\n') # set newline according to your needs here
h = MyFileHandler("foo.log")
編輯:刪除了 3.7 中不存在的errors
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.