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?

d_rez90
  • 804
  • 5
  • 16

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
  • 63,514
  • 5
  • 71
  • 101
1

How about this:

import inspect
os.path.abspath(inspect.stack()[-1][1])
Vor
  • 30,519
  • 41
  • 129
  • 188
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,486
  • 1
  • 20
  • 34