簡體   English   中英

Python 日志記錄 - 檢查日志文件的位置?

[英]Python logging - check location of log files?

了解 Python 日志語句存儲位置的方法是什么?

即如果我這樣做:

import logging
log = logging.getLogger(__name__)
log.info('Test')

我在哪里可以找到日志文件? 另外,當我打電話時:

logging.getLogger(__name__)

這是否與記錄器的行為/保存方式有關?

logging模塊使用附加到記錄器的處理程序來決定消息最終如何、在哪里甚至是否被存儲或顯示。 您也可以默認配置logging以寫入文件。 您應該真正閱讀docs ,但是如果您調用logging.basicConfig(filename=log_file_name)其中log_file_name是您希望將消息寫入的文件的名稱(請注意,您必須在調用logging任何其他內容之前執行此操作) ,然后記錄到所有記錄器的所有消息(除非稍后發生一些進一步的重新配置)將被寫入那里。 請注意記錄器設置的級別; 如果沒記錯的話, info低於默認日志級別,因此您必須在basicConfig的參數中包含level=logging.INFO以及您的消息最終出現在文件中。

至於問題的另一部分, logging.getLogger(some_string)返回一個Logger對象,從根記錄器插入到層次結構中的正確位置,名稱是some_string的值。 不帶參數調用,它返回根記錄器。 __name__返回當前模塊的名稱,因此logging.getLogger(__name__)返回一個名稱設置為當前模塊名稱的Logger對象。 這是與logging使用的常見模式,因為它會導致記錄器結構反映代碼的模塊結構,這通常使日志消息在調試時更加有用。

要獲取簡單文件記錄器的日志位置,請嘗試

logging.getLoggerClass().root.handlers[0].baseFilename

要查找日志文件位置,請嘗試在您的環境中的 Python shell 中實例化您的log對象並查看以下值:

log.handlers[0].stream

一些很好的答案,但最佳答案對我不起作用,因為我使用的是不同類型的文件處理程序,並且 handler.stream 不提供路徑,但提供文件句柄,並從中獲取路徑有點不明顯。 這是我的解決方案:

import logging
from logging.handlers import FileHandler

# note, this will create a new logger if the name doesn't exist, 
# which will have no handlers attached (yet)
logger = logging.getLogger('<name>')

for h in logger.handlers:
    # check the handler is a file handler 
    # (rotating handler etc. inherit from this, so it will still work)
    # stream handlers write to stderr, so their filename is not useful to us
    if isinstance(h, FileHandler):
        # h.stream should be an open file handle, it's name is the path
        print(h.stream.name)

很好的問題@zallarak。 不幸的是,雖然它們很容易創建,但Loggers很難檢查。 這將獲取logger的所有Handlers的文件名:

filenames = []
for handler in logger.handlers:
    try:
        filenames.append(handler.fh.name)
    except:
        pass

try塊處理文件名查找失敗時發生的異常。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM