簡體   English   中英

記錄層次結構與root記錄器?

[英]Logging hierarchy vs. root logger?

在我的代碼的某處,我有類似以下內容:

logger = logging.getLogger('debug0.x')

以我的理解, 只有在我之前做過類似的事情時,它才會響應:

logging.basicConfig(filename='10Nov2010a.txt',level=logging.DEBUG, name='debug0')

注意,該名稱已定義為debug0 但是,我發現如果

logging.basicConfig(filename='10Nov2010a.txt',level=logging.DEBUG)

如果沒有name關鍵字,則上面定義的debug0.x記錄器將做出反應,並寫入日志文件。 我以為只有在命名記錄器時,它才會在第一種情況下做出反應。

我糊塗了。

Python logging模塊按層次結構組織記錄器。 所有記錄器都是根記錄器的后代。 每個記錄器將日志消息傳遞到其父級。

使用getLogger()函數創建新的記錄器。 函數調用logging.getLogger('debug0.x')創建一個記錄器x ,它是debug0的子代,而debug0本身是根記錄器的子代。 登錄到該記錄器時,它將消息傳遞給它的父記錄器,其父記錄將消息傳遞給根記錄器。 您已配置了root記錄器以通過basicConfig()函數登錄到文件,因此您的消息將在那里結束。

如果您簽出代碼或文檔:

>>> print logging.basicConfig.__doc__

    Do basic configuration for the logging system.

    This function does nothing if the root logger already has handlers
    configured. ...............
    A number of optional keyword arguments may be specified, which can alter
    the default behaviour.

    filename  Specifies that a FileHandler be created, using the specified
              filename, rather than a StreamHandler.
    filemode  Specifies the mode to open the file, if filename is specified
              (if filemode is unspecified, it defaults to 'a').
    format    Use the specified format string for the handler.
    datefmt   Use the specified date/time format.
    level     Set the root logger level to the specified level.
    stream    Use the specified stream to initialize the StreamHandler. Note
              that this argument is incompatible with 'filename' - if both
              are present, 'stream' is ignored.

logging.basicConfig根本不使用name參數。 它初始化根記錄器。 盡管getLogger使用“名稱”參數

>>> print logging.getLogger.__doc__

    Return a logger with the specified name, creating it if necessary.

    If no name is specified, return the root logger.

暫無
暫無

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

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