如何在每个记录器的基础上更改Python日志消息的格式? [英] How do I change the format of a Python log message on a per-logger basis?

查看:83
本文介绍了如何在每个记录器的基础上更改Python日志消息的格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在阅读logging 上的文档后,我知道我可以使用代码了像这样执行简单的日志记录:

After reading the documentation on logging, I know I can use code like this to perform simple 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一样在每个记录器的基础上更改这些日志消息的格式?

However, I realised I don't know how to change the format of log messages on a per-logger basis, since basicConfig is a module-level function. This code works for creating different loggers with different levels, names, etc. but is there a way to change the format of those log messages on a per-logger basis as well, in a way similar to 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()

推荐答案

尝试一下

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 了解更多信息

这篇关于如何在每个记录器的基础上更改Python日志消息的格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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