【问题标题】:How do I change the format of a Python log message on a per-logger basis?如何在每个记录器的基础上更改 Python 日志消息的格式?
【发布时间】:2012-07-19 20:59:17
【问题描述】:

阅读documentation on logging后,我知道我可以使用这样的代码来执行简单的日志记录:

import logging

def main():
    logging.basicConfig(filename="messages.log",
                        level=logging.WARNING,
                        format='%(filename)s: '    
                                '%(levelname)s: '
                                '%(funcName)s(): '
                                '%(lineno)d:\t'
                                '%(message)s')

    logging.debug("Only for debug purposes\n")
    logging.shutdown()

main()

但是,我意识到我不知道如何在每个记录器的基础上更改日志消息的格式,因为basicConfig 是一个模块级函数。此代码适用于创建具有不同级别、名称等的不同记录器,但有没有办法以类似于basicConfig 的方式在每个记录器的基础上更改这些日志消息的格式?

import inspect
import logging

def function_logger(level=logging.DEBUG):
    function_name = inspect.stack()[1][3]
    logger = logging.getLogger(function_name)
    logger.setLevel(level)
    logger.addHandler(logging.FileHandler("{0}.log".format(function_name)))
    return logger

def f1():
    f1_logger = function_logger()
    f1_logger.debug("f1 Debug message")
    f1_logger.warning("f1 Warning message")
    f1_logger.critical("f1 Critical message")

def f2():
    f2_logger = function_logger(logging.WARNING)
    f2_logger.debug("f2 Debug message")
    f2_logger.warning("f2 Warning message")
    f2_logger.critical("f2 Critical message")

def main():
    f1()
    f2()
    logging.shutdown()

main()

【问题讨论】:

标签: python logging python-3.x


【解决方案1】:

您必须创建或使用logging.Handler 的现有子类,并使用logger.Formatter 的自定义子类的实例调用其实例的setformatter() 方法。如果您为已附加到要修改其输出的记录器的处理程序设置格式化程序,则很好,否则您必须使用 logging.getLogger() 检索记录器对象并使用实例调用其 addHandler() 方法您将格式化程序设置为参数的处理程序类。

【讨论】:

    【解决方案2】:

    试试这个

    import logging
    
    logger = logging.getLogger('simple_example')
    logger.setLevel(logging.DEBUG)
    # create file handler that logs debug and higher level messages
    fh = logging.FileHandler('spam.log')
    fh.setLevel(logging.DEBUG)
    # create console handler with a higher log level
    ch = logging.StreamHandler()
    ch.setLevel(logging.ERROR)
    # create formatter and add it to the handlers
    formatter = logging.Formatter(
        '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    ch.setFormatter(formatter)
    fh.setFormatter(formatter)
    # add the handlers to logger
    logger.addHandler(ch)
    logger.addHandler(fh)
    
    # 'application' code
    logger.debug('debug message')
    logger.info('info message')
    logger.warn('warn message')
    logger.error('error message')
    logger.critical('critical message')
    

    更多信息请参见http://docs.python.org/howto/logging-cookbook.html#multiple-handlers-and-formatters

    【讨论】:

    • +1,然后再次+1(遗憾的是没有)用于添加代码。我也将它编辑到我的previous answer 中以记录日志问题,并且效果很好。
    • 我总是很惊讶它不像logger = logging.getLogger('mylogger') logger.basicConfig(level=..., format=...)那么简单...
    猜你喜欢
    • 1970-01-01
    • 2016-02-20
    • 1970-01-01
    • 1970-01-01
    • 2011-01-12
    • 2011-10-14
    • 2019-08-04
    • 2020-06-26
    • 2021-01-18
    相关资源
    最近更新 更多