我在这里浏览了 python 日志记录类的教程,没有看到任何可以让我为同一输出创建不同级别的多个日志的内容。最后我想要三个日志:<timestamp>_DEBUG.log
(调试级别)
<timestamp>_INFO.log
(信息级别)
<timestamp>_ERROR.log
(错误级别)
有没有一种方法可以在一个脚本中为同一输入生成多个日志文件?
因此,在实现 @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.log
and debug.log
被创建,但仅error.log
填充有条目。
知道为什么吗?
所以我意识到没有记录任何比警告“更低”的内容。即使我移除过滤器并且debugLogFileHandler.setLevel(logging.DEBUG)
这似乎并不重要。如果我将实际的日志命令设置为logger.warning
或更高,它将打印到日志中。当然,一旦我取消评论debugLogFileHandler.addFilter(LevelFilter(logging.DEBUG))
我没有收到任何日志活动Debug.log
。我很想创建自己的日志级别,但这似乎是一个非常糟糕的主意,以防任何人/任何其他人使用此代码。
好吧,我很愚蠢,忘记设置记录器本身来记录 DEBUG 级别事件。由于默认情况下,日志记录类不会记录低于警告的任何内容,因此它不会记录我发送给它的任何调试信息。
最后感谢@Robert 的过滤器。