使用 Python logger 类为不同的日志级别生成多个日志 [英] using Python logger class to generate multiple logs for different log levels

查看:74
本文介绍了使用 Python logger 类为不同的日志级别生成多个日志的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里浏览了 python 日志类的教程,但没有看到任何可以让我为同一个输出制作不同级别的多个日志的内容.最后我想要三个日志:_DEBUG.log(调试级别)
_INFO.log(信息级别)
_ERROR.log(错误级别)

I looked through the tutorials for the python logging class here and didnt see anything that would let me make multiple logs of different levels for the same output. In the end I would like to have three logs: <timestamp>_DEBUG.log (debug level)
<timestamp>_INFO.log (info Level)
<timestamp>_ERROR.log (error level)

有没有办法在一个脚本中为同一个输入生成多个日志文件?

Is there a way to, in one script, generate multiple log files for the same input?

<-------------更新#1-------------------------->
因此,在实施@robert 的建议时,我现在遇到了一个小问题,可能是因为没有完全理解他的代码中正在执行的操作.

<-------------UPDATE #1-------------------------->
So in implementing @robert's suggestion, I now have a small issue, probably due to not fully understanding what is being done in his code.

这是我在 scriptRun.py 中的代码

Here is my code in 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	oscripts"):
    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 填充了条目.

Now to my issue: running scriptRun.py does not throw any errors when i run it, and error.log and debug.log are created, but only error.log is populated with entries.

知道为什么吗?

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

<------------------------Update #2----------------------->

所以我意识到没有记录低于"警告的内容.即使我删除了过滤器和 debugLogFileHandler.setLevel(logging.DEBUG),它似乎也无所谓.如果我将实际日志命令设置为 logger.warning 或更高,它将打印到日志.当然,一旦我取消注释 debugLogFileHandler.addFilter(LevelFilter(logging.DEBUG)),我在 Debug.log 中就没有日志活动.我很想创建自己的日志级别,但这似乎是一个非常糟糕的主意,以防任何人/其他任何人使用此代码.

So I realized that nothing is being logged that is "lower" than warning. even if i remove the filters and debugLogFileHandler.setLevel(logging.DEBUG) it does not seem to matter. If I set the actual log command to logger.warning or higher, it will print to the logs. Of course once I uncomment debugLogFileHandler.addFilter(LevelFilter(logging.DEBUG)) I get no log activity in Debug.log. I;m tempted to just make my own log level, but that seems like a really bad idea, in case anyone/anything else uses this code.

<-------------------------最终更新-------------------->
好吧,我很愚蠢,忘记将记录器本身设置为记录 DEBUG 级别的事件.由于默认情况下,日志类不会记录任何低于警告的内容,因此它不会记录我发送的任何调试信息.

<-------------------------Final UPDATE--------------------->
Well I was stupid and forgot to set the logger itself to log DEBUG level events. Since by default the logging class doesn't log anything below warning, it wasnt logging any of the debug information I send it.

最后感谢@Robert 提供过滤器.

Final thanks and shoutout to @Robert for the filter.

推荐答案

创建多个处理程序,每个处理程序对应一个输出文件(INFO.log、DEBUG.log 等).

Create multiple Handlers, each for one output file (INFO.log, DEBUG.log etc.).

为每个处理程序添加一个仅允许特定级别的过滤器.

Add a filter to each handler that only allows the specific level.

例如:

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))

这篇关于使用 Python logger 类为不同的日志级别生成多个日志的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆