0

I have a custom logger defined in

/utils/my_logger.py

class MyLogger():
    def __init__(self, name, path_of_module):
        self.logger_name = name
        self.path = path_of_module

    def get_logger(self):
        ...
        #setLevel, formatter, handler, etc.
        return logger

say, in another file somewhere I import and instantiate MyLogger..

/some/path/to/foo.py

handler = MyLogger("testing", os.path.realpath(__file__))
log = handler.get_logger()

Is there any way to do this so that I don't have to explicitly write os.path.realpath(__file__) as an argument every time I instantiate the logger?

drez90
  • 814
  • 5
  • 17

3 Answers3

4

You can use the inspect module to look for the caller on the stack. From there, you can get the caller's module and __file__. Look at Get name of calling function's module in Python - its getting module name but the same goes for the file name.

Community
  • 1
  • 1
tdelaney
  • 73,364
  • 6
  • 83
  • 116
1

How about this:

import inspect
os.path.abspath(inspect.stack()[-1][1])
Vor
  • 33,215
  • 43
  • 135
  • 193
0

[Edit]: changed to os.getcwd() Do it in the init method,

def __init__(self, name):
        self.logger_name = name
        self.path = os.getcwd()

Isn't that better ?!

e-nouri
  • 2,576
  • 1
  • 21
  • 36