Trying_hard
Trying_hard

Reputation: 9501

Python OS get current File name on imported module

I am trying to write a logging module that I can use over and over again. The logging is not the problem. I want to call my logging module from any script and not have to pass the params for the logging file.

If I have a test script called mytest.py how would I return this name in the import logging module. I have tried this in the logging script itself but it returns the name of that file and not the file I am trying to log.

my_test.py:

from my_logger  import logging

info.logging("something here")
print("something here")

if __name__ == "__main__":
    logging()

I would expect the log file to be called my_test.log, but currently it is being named logging.log

Here is the part from the logging script:

def logging(filename=False, level=DEFAULT_LOG_LEVEL):
    if filename is False:
        file_ext = os.path.basename(__file__) # Need this to be my_test.py
        filename = ("C:/Users/Logs/{0}").format(file_ext)
        "Start logging with given filename and level."
        #print(filename)
        logging.basicConfig(filename=filename, level=LEVELS[level])
    else:
        "Start logging with given filename and level."
        logging.basicConfig(filename=filename, level=LEVELS[level])

Upvotes: 0

Views: 500

Answers (2)

Ozgur Vatansever
Ozgur Vatansever

Reputation: 52143

Assuming your compiler is CPython (thanks to Matthew Trevor);

You can use inspect.getouterframes to get the caller's frame, plus the filename and line number etc.

import inspect

def logging(filename=False, level=DEFAULT_LOG_LEVEL):
    if filename is False:
        caller_file = inspect.getouterframes(inspect.currentframe())[1][3] 
        # prints /home/foo/project/my_test.py
    ...

Upvotes: 1

Matthew Trevor
Matthew Trevor

Reputation: 14962

The __file__ binding you use in your logging function will hold the value of the file it's scoped in. You need to pass in the calling module's __file__ to get the behaviour you want:

# my_test.py

...

if __name__ == "__main__":
    logging(__file__)

I'm surprised that your log file was called logging.log and not my_logger.log, though, as that's the name of the file in which the logging function is defined.

Upvotes: 0

Related Questions