簡體   English   中英

使用Python logger類為不同的日志級別生成多個日志

[英]using Python logger class to generate multiple logs for different log levels

我在這里瀏覽了python日志類的教程,並沒有看到任何可以讓我為同一輸出制作不同級別的多個日志的東西。 最后我想有三個日志: <timestamp>_DEBUG.log (調試級別)
<timestamp>_INFO.log (信息級別)
<timestamp>_ERROR.log (錯誤級別)

有沒有辦法在一個腳本中為同一輸入生成多個日志文件?

<-------------更新#1 -------------------------->
所以在實現@robert的建議時,我現在有一個小問題,可能是由於沒有完全理解他的代碼中正在做什么。

這是我在scriptRun.py中的代碼

import os
import logging

logger = logging.getLogger("exceptionsLogger")
debugLogFileHandler = logging.FileHandler("Debug.log")
errorLogFileHandler = logging.FileHandler("Error.Log")
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
errorLogFileHandler.setFormatter(formatter)
debugLogFileHandler.setFormatter(formatter)
logger.addHandler(debugLogFileHandler)
logger.addHandler(errorLogFileHandler)

class LevelFilter(logging.Filter):
    def __init__(self, level):
        self.level = level
    def filter(self, record):
        return record.levelno == self.level
debugLogFileHandler.addFilter(LevelFilter(logging.DEBUG))
errorLogFileHandler.addFilter(LevelFilter(logging.ERROR))

directory = []
for dirpath, dirnames, filenames in os.walk("path\to\scripts"):
    for filename in [f for f in filenames if f.endswith(".py")]:
        directory.append(os.path.join(dirpath, filename))
for entry in directory:
    execfile(entry)
    for lists in x:
        if lists[0] == 2:
            logger.error(lists[1]+"   "+lists[2])
        elif lists[0] == 1:
            logger.debug(lists[1]+"   "+lists[2])

這是一個運行的例子是:

import sys

def script2Test2():
    print y
def script2Ttest3():
    mundo="hungry"

global x 
x = []

theTests = (test2, test3)

for test in theTests:
    try:
        test()
        x.append([1,test.__name__," OK"])
    except:
        error = str(sys.exc_info()[1])
        x.append([2,test.__name__,error])

現在我的問題是:運行scriptRun.py不會拋出任何錯誤,並且會創建error.logdebug.log ,但只有error.log填充了條目。

任何想法為什么?

<------------------------更新#2 ---------------------- - >

所以我意識到沒有任何記錄比警告更“低”。 即使我刪除過濾器和debugLogFileHandler.setLevel(logging.DEBUG)它似乎並不重要。 如果我將實際的日志命令設置為logger.warning或更高,它將打印到日志。 當然,一旦我取消注釋debugLogFileHandler.addFilter(LevelFilter(logging.DEBUG))我在Debug.log沒有得到任何日志活動。 我很想制作我自己的日志級別,但這似乎是一個非常糟糕的主意,以防任何人/其他任何人使用此代碼。

<------------------------- Final UPDATE --------------------->
好吧,我是愚蠢的,忘了設置記錄器本身來記錄DEBUG級事件。 因為默認情況下,日志記錄類不記錄任何低於警告的內容,所以它沒有記錄我發送的任何調試信息。

最后感謝@Robert過濾器。

創建多個處理程序,每個處理程序用於一個輸出文件(INFO.log,DEBUG.log等)。

為每個僅允許特定級別的處理程序添加過濾器。

例如:

import logging

# Set up loggers and handlers.
# ...

class LevelFilter(logging.Filter):
    def __init__(self, level):
        self.level = level

    def filter(self, record):
        return record.levelno == self.level

debugLogFileHandler.addFilter(LevelFilter(logging.DEBUG))
infoLogFileHandler.addFilter(LevelFilter(logging.INFO))

暫無
暫無

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

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