简体   繁体   English

logging.info('…',stack_info = True)对于Python2

[英]logging.info('…', stack_info=True) for Python2

Python3 has the argument stack_info for logging.info() : Python3具有用于logging.info()的参数stack_info

https://docs.python.org/dev/library/logging.html#logging.Logger.debug https://docs.python.org/dev/library/logging.html#logging.Logger.debug

How to get this in Python2? 如何在Python2中获得它?

The following module wrap the logging module with support to stack_info keyword argument. 以下模块将日志记录模块包装为支持stack_info关键字参数。 you can import this module and call the getLogger method similar to how you work with logging module. 您可以导入此模块并调用与记录模块类似的getLogger方法。

import logging
import logging.handlers
from functools import partial
logger = logging.getLogger()

old_critical = logger.critical
old_error = logger.error
old_warning = logger.warning
old_info = logger.info
old_debug = logger.debug
import traceback

def custom_log(old_log, message, *args, **kwargs):
    if kwargs.get("stack_info"):
        message = message + reduce(lambda x,y: x+y, traceback.format_stack(), "")
    if kwargs.get("stack_info") is not None:
        del kwargs["stack_info"]
    old_log(message, *args, **kwargs)

logger.critical = partial(custom_log, old_critical)
logger.error = partial(custom_log, old_error)
logger.warning = partial(custom_log, old_warning)
logger.info = partial(custom_log, old_info)
logger.debug = partial(custom_log, old_debug)

def new_getLogger(logger_name="root"):
    return logger

from logging import *
getLogger = new_getLogger

PS - One downside to this approach is it will make one extra function call and that also will be visible in stack trace PS-这种方法的缺点是它将进行一个额外的函数调用,并且在堆栈跟踪中也将可见

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM