使用python日志包,如何将其他格式插入到具有自己的格式化程序的多个记录器处理程序中?

时间:2011-01-20 02:26:58

标签: python logging formatter

我有一个带有多个处理程序的记录器,它们有自己的格式化程序。现在我想添加一个缩进功能,在运行时控制缩进级别。我希望所有处理程序的消息都能得到这个缩进。我试图将其创建为过滤器,但发现我似乎无法更改邮件内容。然后我尝试了它作为格式化程序,但我每个处理程序只能有一个。如何在不显式更改每个处理程序的格式化程序的情况下添加此类缩进?
我应该提一下,我所拥有的格式化程序之一是为输出添加颜色的类。它不是一个简单的格式字符串。


另外,我正在使用配置文件。理想情况下,我希望能够从那里开车。但是,我需要修改缩进格式化程序的状态(例如设置缩进级别),但我不知道如何到达那个特定的格式化程序,因为没有logger.getFormatter("by_name")方法。
为了澄清,我需要访问特定的格式化程序实例,主要是为了动态调整格式。该实例已由文件中的logging.config创建。我找不到任何访问器方法,这些方法可以让我获得给定名称的特定格式化程序。

3 个答案:

答案 0 :(得分:4)

#!/usr/bin/env python

import logging
from random import randint

log = logging.getLogger("mylog")
log.setLevel(logging.DEBUG)

class MyFormatter(logging.Formatter):
    def __init__(self, fmt):
        logging.Formatter.__init__(self, fmt)

    def format(self, record):
        indent = " " * randint(0, 10) # To show that it works
        msg = logging.Formatter.format(self, record)
        return "\n".join([indent + x for x in msg.split("\n")])

# Log to file
filehandler = logging.FileHandler("indent.txt", "w")
filehandler.setLevel(logging.DEBUG)
filehandler.setFormatter(MyFormatter("%(levelname)-10s %(message)s"))
log.addHandler(filehandler)

# Log to stdout too
streamhandler = logging.StreamHandler()
streamhandler.setLevel(logging.INFO)
streamhandler.setFormatter(MyFormatter("%(message)s"))
log.addHandler(streamhandler)

# Test it
log.debug("Can you show me the dog-kennels, please")
log.info("They could grip it by the husk")
log.warning("That's no ordinary rabbit!")
log.error("Nobody expects the spanish inquisition")
try:
    crunchy_frog()
except:
    log.exception("It's a real frog")

结果:

    They could grip it by the husk
    That's no ordinary rabbit!
          Nobody expects the spanish inquisition
         It's a real frog
         Traceback (most recent call last):
           File "./logtest2.py", line 36, in 
             crunchy_frog()
         NameError: name 'crunchy_frog' is not defined

我不确定我理解你的第二个问题。

答案 1 :(得分:0)

好的,这是让我几乎满足我需要的一种方式。对LogRecord进行子类化以覆盖getMessage,以便将indent和subclass logger插入到makeRecord中:

import logging
import logging.config  

################################################################################
class IndentingLogger(logging.Logger):
    """A Logger subclass to add indent on top of any logger output
    """
    ############################################################################
    def __init__(self, name = 'root', logging_level = logging.NOTSET):
        "Constructor to keep indent persistent"
        logging.Logger.__init__(self, name, logging_level)
        self.indenter = IndentedRecord("", logging.NOTSET, "", 0, None, None, None, None, None)

    ############################################################################
    def makeRecord(self, name, level, fn, lno, msg, args, exc_info, func=None, extra=None):
        return self.indenter.set_record(name, level, fn, lno, msg, args, exc_info, func, extra)


################################################################################
class IndentedRecord(logging.LogRecord):
    """A LogRecord subclass to add indent on top of any logger output
    """
    ######## Class data #########
    DEFAULT_INDENT_STR = '    '

    ############################################################################
    def __init__(self, name, level, fn, lno, msg, args, exc_info, func=None, extra=None):
        "Constructor"
        logging.LogRecord.__init__(self, name, level, fn, lno, msg, args, exc_info, func)
        self._indent_level = 0
        self._indent_str_base = IndentedRecord.DEFAULT_INDENT_STR
        self._indent_str = ""    # cache it

    ############################################################################
    def set_record(self, name, level, fn, lno, msg, args, exc_info, func=None, extra=None):
        "Constructs the base record"
        logging.LogRecord.__init__(self, name, level, fn, lno, msg, args, exc_info, func)
        return self

    ################################################################################
    def getMessage(self):
        "Adds indent on top of the normal getMessage result"

        # Call base class to get the formatted message
        message = logging.LogRecord.getMessage(self)

       # Now insert the indent
        return self._indent_str + message

    ################################################################################
    def indent(self, step = 1):
        "Change the current indent level by the step (use negative to decrease)"
        self._indent_level += step
        if self._indent_level < 0:
            self._indent_level = 0
        self._indent_str = self._indent_str_base * self._indent_level

    ################################################################################
    def set_indent_str(self, chars):
        "Change the current indent string"
        if not isinstance(chars, str):
            raise ValueError("Argument must be a string. Got %s" % chars)
        self._indent_str_base = chars

logging.config.fileConfig("reporter.conf")
logging.setLoggerClass(IndentingLogger)
logger = logging.getLogger('root') # will be wrong logger, if without argument

logger.debug("debug message")
logger.info("info message")
logger.indenter.indent(+1)
logger.warn("Indented? warn message")
logger.indenter.set_indent_str("***")
logger.error("Indented? error message: %s", "Oops, I did it again!")
logger.indenter.indent(+1)
logger.error("Indented? error message: %s", "Oops, I did it again!")
logger.indenter.indent(-1)
logger.critical("No indent; critical message")

结果是(现实着色):

Debug: debug message
Info: info message
Warning:     Indented? warn message
Error:     Indented? error message: Oops, I did it again!
Error: ******Indented? error message: Oops, I did it again!
Internal Error: ***No indent; critical message

不知何故,日志级别的字符串仍然潜入前面,所以它不是我想要的。此外,这是一个尴尬 - 对于这样一个简单的功能太多了:(
更好的想法?

答案 2 :(得分:0)

这是另一个,hacky,但很简单。我的所有处理程序的消息总是以消息级别字符串开头。只需在每次缩进更改时修改这些darn字符串:

# (make a LEVELS dict out of all the logging levels first)    
def indent(self, step = 1):
        "Change the current indent level by the step (use negative to decrease)"
        self._indent_level += step
        if self._indent_level < 0:
            self._indent_level = 0
        self._indent_str = self._indent_str_base * self._indent_level
        for lvl in LEVELS:
            level_name = self._indent_str + LEVELS[lvl]
            logging.addLevelName(lvl, level_name)

(有关缩进功能的内容,请参阅我的其他答案)
现在压头可以是一个独立的类,而不会弄乱日志记录过程的细节。只要消息包含级别字符串,缩进就会在那里,即使某些东西在它之前。一般不理想,但可能对我有用。
任何人都有更多的想法适用于任何msg格式?