'Function to print the file name of the file that is calling the function

I want to create a log function that logs the name of the file that is calling the log function followed by the message I want to log 'message'

functions.py

def log(text):
    print(os.path.basename(__file__)+": "+text)

main.py

log('message')

this returns:

functions.py: message

I want it to return:

main.py: message



Solution 1:[1]

You can do it by first reaching back through the interpreter's stack using the inspect module and retrieving the name of the path to caller's file, and then extracting the file's name from that (which is very easy using the pathlib module).

main.py:

from functions import log

log('message')

functions.py:

import inspect
from pathlib import Path

def log(text):
    caller_path = Path(inspect.stack()[1][1])
    print(f'{caller_path.name}: {text}')

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 martineau