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

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

问题描述

我在这里查看了python日志记录类的教程,并没有看到任何让我为同一个输出创建不同级别的多个日志。最后,我想有三个日志:
< timestamp> _DEBUG.log (调试级别)

< timestamp> _INFO.log (info Level)

< timestamp> _ERROR.log

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



< ------------- UPDATE#1 -------------------------->

所以在实现@罗伯特的建议,我现在有一个小问题,可能是由于不完全理解他的代码中正在做什么。



这是我的代码scriptRun.py
$ b

  import os 
导入日志

logger = logging.getLogger( (Error.Log)
debugLogFileHandler = logging.FileHandler(Debug.log)
errorLogFileHandler = logging.FileHandler(Error.Log)
formatter = logging.Formatter('%(asctime) s%(levelname)s%(message)s')
errorLogFileHandler.setFormatter(formatter)
debugLogFileHandler.setFo rmatter(formatter)
logger.addHandler(debugLogFileHandler)
logger.addHandler(errorLogFileHandler)
$ b $ 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 = []
在os.walk中的dirpath,dirnames,filenames(path \to\如果f.endswith(.py)]:
directory.append(os.path.join(dirpath,filename))
在目录中输入:
execfile(条目)
列表中的x:
如果列表[0] == 2:
logger.error(lists [1] + + list [2])
elif lists [0] == 1:
logger.debug(lists [1] ++ lists [2])

一个这样运行的例子是:


$ b

  import sys 

def script2Test2():
print y
def script2Ttest3():
mundo =饥饿

全球x
x = []

theTests =(test2,test3)

测试在测试中:
试试:
test()
x.append([1,test .__ name__,OK])
除了:
error = str (sys.exc_info()[1])$ ​​b $ b x.append([2,test .__ name __,error])

现在到我的问题:运行 scriptRun.py 不会引发任何错误,当我运行它, error.log debug.log 被创建,但是只有 error.log 填充了条目。 / p>

任何想法为什么?

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



所以我意识到没有任何东西被记录下来,比警告低。即使我删除过滤器和 debugLogFileHandler.setLevel(logging.DEBUG)它似乎并不重要。如果我将实际的日志命令设置为 logger.warning 或更高,它将打印到日志。当然,我取消注释 debugLogFileHandler.addFilter(LevelFilter(logging.DEBUG))我没有在 Debug.log 。我试图做自己的日志级别,但这似乎是一个非常糟糕的主意,以防万一/其他人使用这个代码。



< -----------------------最终更新--------------------->

那么我是愚蠢的,忘了设置记录本身来记录DEBUG级别的事件。由于默认情况下,日志记录类不会记录任何低于警告,它不记录任何我发送的调试信息。



最后,感谢@Robert的过滤器的支持。

解决方案

为每个输出文件(INFO.log,DEBUG.log等)创建多个处理程序。



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



例如:

 导入记录

#设置记录器和处理程序。
$ ...

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

def filter(self,record):
return record.levelno == self.level
$ b $ debugLogFileHandler.addFilter(LevelFilter(logging.DEBUG))
infoLogFileHandler.addFilter (LevelFilter(logging.INFO))


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?

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

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

an example of what this is running is:

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

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.

any idea why?

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

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.

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

Final thanks and shoutout to @Robert for the filter.

解决方案

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.

For example:

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记录器类为不同的日志级别生成多个日志的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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