首頁  >  文章  >  後端開發  >  如何在 Python 中同時記錄到標準輸出和日誌檔案?

如何在 Python 中同時記錄到標準輸出和日誌檔案?

DDD
DDD原創
2024-10-18 18:55:29937瀏覽

How to Log to Stdout and Log File Simultaneously in Python?

在Python 中同時將日誌寫入標準輸出和日誌檔案

控制日誌輸出對於在Python 中調試和捕獲重要資訊關重要。日誌記錄模組提供了將訊息記錄到檔案的廣泛功能。但是,將日誌顯示到控制台(標準輸出)以便立即可見也是有益的。

解決方案:

確保所有日誌訊息都輸出到標準輸出除了指定的日誌檔案之外,您還可以透過向根記錄器添加logging.StreamHandler ()來擴充日誌記錄模組的功能。

實作:

<code class="python">import logging
import sys

# Capture stdout
stdout = sys.stdout

# Create a root logger
root = logging.getLogger()

# Set the logging level (DEBUG in this case)
root.setLevel(logging.DEBUG)

# Define the StreamHandler
handler = logging.StreamHandler(stdout)

# Configure the message format
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)

# Add the StreamHandler to the root logger
root.addHandler(handler)</code>

透過此修改,使用logger.warning、logger.ritic 和logger.error 等方法記錄的所有訊息都會寫入配置的日誌檔案並直接顯示到st​​dout。這簡化了故障排除並確保可以輕鬆地立即存取訊息以進行檢查。

以上是如何在 Python 中同時記錄到標準輸出和日誌檔案?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn