【问题标题】:Different levels of logging in pythonpython中不同级别的日志记录
【发布时间】:2012-02-08 21:24:04
【问题描述】:

我想做一些我认为很简单的事情。

其实是用python日志模块,我对日志很感兴趣 命令行上的所有内容都在命令给出的级别 行参数,并记录到文件到一个固定的 DEBUG 级别。

创建两个不同级别的不同记录器不起作用,但是 设置两个不同处理程序的级别都添加到根 记录器也不起作用,所以关于我应该如何实际做的任何想法? (阅读其他链接,第二种方法应该有效,所以我在做其他愚蠢的事情吗?)

这是目前设置我的日志系统的代码:

class LoggerSetup(object):
    """Setup the different logger objects
    """

    def __init__(self):
        self.root_logger = logging.getLogger()
        self.shell_hdlr = logging.StreamHandler()

    #TODO: add another logging handler which stores to a temporary file
    #which should be cleaned up later
    def setup_shell_logger(self, log_level):
        self.root_logger.setLevel(LOG_LEVELS[log_level])
        # in this way the root logger is not set but the handlers are set
        self.shell_hdlr = logging.StreamHandler()
        self.shell_hdlr.setLevel(LOG_LEVELS[log_level])
        self.shell_hdlr.setFormatter(StarFormatter())
        #FIXME: add the support for regular expression exclusion too
        self.root_logger.addHandler(self.shell_hdlr)

    def setup_log_include(self, log_include):
        """Set up the filter to include log messages
        """
        if log_include:
            incl = FilterInclude(log_include)
            self.shell_hdlr.addFilter(incl)

    def setup_log_exclude(self, log_exclude):
        """Set up the filters to exclude log messages
        """
        if log_exclude:
            excl = FilterExclude(log_exclude)
            self.shell_hdlr.addFilter(excl)

    def setup_file_logging(self):
        """Set up the file logger, which always logs in DEBUG mode
        even if the top level logger is set to another level
        """
        #XXX: not working, one possible way to make it work is to create
        #only one log, and different handler/filters to make to handle all
        #the different outputs
        file_handler = logging.FileHandler(LOG_FILENAME)
        # the file logging is always in debug mode
        file_handler.setLevel(logging.DEBUG)
        formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s - %(asctime)s')
        file_handler.setFormatter(formatter)
        self.root_logger.addHandler(file_handler)

【问题讨论】:

  • “但是设置两个不同处理程序的级别都添加到根记录器不起作用”?你能澄清一下吗?

标签: python logging


【解决方案1】:

这是我在所有 Python 命令行应用程序中都使用的东西。这有点冗长,但您应该能够获得一个接受可选参数的记录器,以在任何级别创建控制台记录器,而不管文件中记录了什么:

#!/usr/bin/env python
import logging
from argparse import ArgumentParser

COMPANY_LOGGER = 'COMPANY.Python.Logger'
CONSL_LEVEL_RANGE = range(0, 51)
LOG_FILE = 'company.log'
FORMAT_STR = '%(asctime)s %(levelname)s %(message)s'

parser = ArgumentParser()
parser.add_argument('-c', '--console-log', metavar='ARG',
                    type=int, choices=range(0, 51),
                    action='store', dest='console_log',
                    default=None,
                    help='Adds a console logger for the level specified in the range 1..50')

args = parser.parse_args()

# Create logger
logger = logging.getLogger(COMPANY_LOGGER)
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter(FORMAT_STR)

# Add FileHandler and only log WARNING and higher
fh = logging.FileHandler(LOG_FILE)
fh.name = 'File Logger'
fh.level = logging.WARNING
fh.formatter = formatter
logger.addHandler(fh)

# Add optional ConsoleHandler
if args.console_log:
    ch = logging.StreamHandler()
    ch.name = 'Console Logger'
    ch.level = args.console_log
    ch.formatter = formatter
    logger.addHandler(ch)

logger.debug('DEBUG')
logger.info('INFO')
logger.warning('WARNING')
logger.critical('CRITICAL')

从命令行运行时,我们可以看到记录级别的差异。

-c1 等同于“DEBUG 及更高版本”(最冗长),但 company.log 仍仅记录 WARNING 及更高版本:

~ zacharyyoung$ ./so.py -c1
2012-01-12 08:59:50,086 DEBUG DEBUG
2012-01-12 08:59:50,086 INFO INFO
2012-01-12 08:59:50,087 WARNING WARNING
2012-01-12 08:59:50,087 CRITICAL CRITICAL

~ zacharyyoung$ cat company.log 
2012-01-12 08:59:50,087 WARNING WARNING
2012-01-12 08:59:50,087 CRITICAL CRITICAL

-c20 等于 INFO:

~ zacharyyoung$ ./so.py -c20
2012-01-12 09:00:09,393 INFO INFO
2012-01-12 09:00:09,393 WARNING WARNING
2012-01-12 09:00:09,393 CRITICAL CRITICAL

~ zacharyyoung$ cat company.log 
2012-01-12 08:59:50,087 WARNING WARNING
2012-01-12 08:59:50,087 CRITICAL CRITICAL
2012-01-12 09:00:09,393 WARNING WARNING
2012-01-12 09:00:09,393 CRITICAL CRITICAL

【讨论】:

  • +1 只是一个建议:如果您使用 parser.add_argument 方法的 type=intchoices=xrange(51) 关键字,我认为您可以避免定义 getConsoleLevel 函数。请参阅end of this section on the doc。并且您可以设置21 的默认值,并获得与logging 模块相同的默认级别。
  • @logc:谢谢你的建议......我不知道为什么我以前没有这样做(也许我担心帮助声明的打印方式),但我可以看到仅使用内置插件也可以正常工作。谢谢你:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-03-26
  • 1970-01-01
  • 2016-02-20
  • 2020-11-19
  • 2019-12-06
  • 1970-01-01
  • 2021-10-29
相关资源
最近更新 更多