有没有办法使用python日志记录从调用者的范围打印

时间:2015-01-29 21:42:38

标签: python logging

有没有办法使用python日志记录从调用者的范围进行打印, 类似于warning.warn的工作方式?

我正在寻找类似的东西:

logging.basicConfig(format='%(levelname)s - %(funcName):%(message)s', level=logging.DEBUG)
logger = logging.getLogger(__name__)

def step(msg):
    logger.info(msg, stacklevel=1)

def func1():
    step("my message")

这会打印出来

INFO - func1: my message

1 个答案:

答案 0 :(得分:0)

在挖掘warning.warn代码和记录文档之后。 找到了一种获得我想要的方式:

import sys
import logging

logger = logging.getLogger(__name__)

def step(msg, stacklevel=1):

    # copied from warning stdlib, with adding function name
    try:
        caller = sys._getframe(stacklevel)
    except ValueError:
        globals = sys.__dict__
        lineno = 1
        func = None
    else:
        globals = caller.f_globals
        lineno = caller.f_lineno
        func = caller.f_code.co_name
    if '__name__' in globals:
        module = globals['__name__']
    else:
        module = "<string>"
    filename = globals.get('__file__')
    if filename:
        fnl = filename.lower()
        if fnl.endswith((".pyc", ".pyo")):
            filename = filename[:-1]
    else:
        if module == "__main__":
            try:
                filename = sys.argv[0]
            except AttributeError:
                # embedded interpreters don't have sys.argv, see bug #839151
                filename = '__main__'
        if not filename:
            filename = module

    record = logger.makeRecord(module, logging.INFO, filename, lineno, msg, None, sys.exc_info(), func=func, extra=None)
    logger.handle(record)

太糟糕了,这种能力并没有内置于记录......