简体   繁体   English

有没有一种方法可以使用python日志记录从调用方的范围进行打印

[英]Is there a way to use python logging to print from the scope of the caller

Is there a way to use python logging to print from the scope of the caller, similar to how warning.warn is working ? 有没有一种方法可以使用python日志记录从调用方的范围进行打印,类似于warning.warn的工作方式如何?

I was looking for something like that: 我一直在寻找这样的东西:

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")

and this would print out 这将打印出来

INFO - func1: my message

After digging inside warning.warn code, and logging documentation. 在挖掘了warning.warn代码并记录文档之后。 found a way get what I wanted: 找到了一种获得我想要的方法:

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)

Too bad this kind of capability isn't built into logging... 遗憾的是,日志记录功能并未内置这种功能...

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

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