0

I created a custom formatter as described here.

Then I've tried to embed the logger and its initialization into a singleton, with the following code:

import logging

class _Logger:
    _instance = None

    def __init__(self):
        self.logger = logging.getLogger("LeApp")
        self.logger.setLevel(logging.DEBUG)
        ch = logging.StreamHandler()
        ch.setLevel(logging.DEBUG)
        ch.setFormatter(CustomFormatter())
        self.logger.addHandler(ch)


def Logger() -> _Logger:
    if not _Logger._instance:
        _Logger._instance = _Logger()
    return _Logger._instance


def MYLOG(iMessage: str):
    Logger().logger.info(iMessage)


def MYDBG(iMessage: str):
    Logger().logger.debug(iMessage)


def MYWAR(iMessage: str):
    Logger().logger.warning(iMessage)


def MYERR(iMessage: str):
    Logger().logger.error(iMessage)


def CRITICAL(iMessage: str):
    Logger().logger.critical(iMessage)

However now, the information displayed in the logs it's not the line number and filename of where the warning is raised, but it's just the filename/linenumber of this python file.

[2021-08-01 10:30:32,889.889] p42815 {Logger2.py:58} WARNING - Object was None

How is the logging library able to show that information?

HAL9000
  • 3,562
  • 3
  • 25
  • 47

1 Answers1

0

Starting from the suggestion in the comments, here's my solution:

import inspect

def getCaller() -> str:
    aFrame = sys._getframe(2)
    info = inspect.getframeinfo(aFrame)
    return os.path.basename(info.filename) + ":" + str(info.lineno)


def MYLOG(iMessage: str):
    Logger().logger.info(getCaller() + " - " + iMessage)
HAL9000
  • 3,562
  • 3
  • 25
  • 47