Как я могу получить предыдущий номер строки исходного кода, который вызывает вход в систему напрямую? - PullRequest
0 голосов
/ 31 мая 2018

У меня есть этот код:

log.py

from .color import Color
import logging

class Log:
    logging.basicConfig(format='%(asctime)s,%(msecs)d %(levelname)-8s [%(filename)s:%(lineno)d] %(message)s',
                        datefmt='%d-%m-%Y:%H:%M:%S',
                        level=logging.INFO)
    logger = logging.getLogger('anywordcanbethis')

    @classmethod
    def warning(self, msg):
        Log.logger.warning(Color.fg.yellow + msg + Color.reset)

    @classmethod
    def error(self, msg):
        Log.logger.error(Color.fg.red + msg + Color.reset)

    @classmethod
    def debug(self, msg):
        Log.logger.info(Color.fg.pink + msg + Color.reset)

Как вы можете видеть, для этого нужно настроить параметры ведения журнала в этом классе, чтобы мои другие проекты легко могли использоватьрегистратор так, как я хочу использовать, например:

import Log

Log.warning("BLAHBLAH") ->
31-05-2018:18:06:45,313 WARNING  [log.py:12] "BLAHBLAH" (yellow)
Log.error("BLAHBLAH") ->
31-05-2018:18:13:43,481 ERROR    [log.py:16] "BLAHBLAH" (red)

проблема в том, что напечатанный номер строки всегда будет log.py:12 <- вот так, чего я не хочу.Я хочу проверить, какой файл называется Log.warning, Log.error ..., который может находиться в стеке на один уровень выше. </p>

Какие варианты я должен попробовать при ведении журнала?

Спасибо

1 Ответ

0 голосов
/ 31 мая 2018

Вы можете попробовать использовать FindCaller() из документов :

Logger.findCaller ()

Finds the caller’s source filename and line number. Returns the filename, line number and function name as a 3-element tuple.

Changed in version 2.4: The function name was added. In earlier versions, the filename and line number were returned as a 2-element
tuple.

Ради интереса, вот метод findCaller (я заметил, что это возвращает 2-элементный кортеж, таким образом, это из <2.4): </p>

def findCaller(self):
    """
    Find the stack frame of the caller so that we can note the source
    file name and line number.
    """
    rv = (None, None)
    frame = inspect.currentframe().f_back
    while frame:
        sfn = inspect.getsourcefile(frame)
        if sfn:
            sfn = os.path.normcase(sfn)
        if sfn != _srcfile:
            #print frame.f_code.co_code
            lineno = inspect.getlineno(frame)
            rv = (sfn, lineno)
            break
        frame = frame.f_back
    return rv 

Я нашел последнюю версию:

def findCaller(self, stack_info=False):
    """
    Find the stack frame of the caller so that we can note the source
    file name, line number and function name.
    """
    f = currentframe()
    #On some versions of IronPython, currentframe() returns None if
    #IronPython isn't run with -X:Frames.
    if f is not None:
        f = f.f_back
    rv = "(unknown file)", 0, "(unknown function)", None
    while hasattr(f, "f_code"):
        co = f.f_code
        filename = os.path.normcase(co.co_filename)
        if filename == _srcfile:
            f = f.f_back
            continue
        sinfo = None
        if stack_info:
            sio = io.StringIO()
            sio.write('Stack (most recent call last):\n')
            traceback.print_stack(f, file=sio)
            sinfo = sio.getvalue()
            if sinfo[-1] == '\n':
                sinfo = sinfo[:-1]
            sio.close()
        rv = (co.co_filename, f.f_lineno, co.co_name, sinfo)
        break
    return rv
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...