0

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

0blex
  • 3
  • 1
  • Does this answer your question? [how to get the caller's filename, method name in python](https://stackoverflow.com/questions/13699283/how-to-get-the-callers-filename-method-name-in-python) – mkrieger1 Apr 15 '22 at 17:02
  • why not pass the caller's file path as an argument to the function? – Kurt Apr 15 '22 at 17:29
  • @Kurt: While that would work, it could get somewhat tedious if it needs to be done many times, and it will produce erroneous results if the name of the script using it is ever changed and all the calls in it manually changed — in other words adds another dependency to the code in the file. – martineau Apr 15 '22 at 17:46
  • @martineau even if you just call `log(__file__, 'Log this message')`? – Kurt Apr 15 '22 at 18:10
  • 1
    @Kurt: Good point — just not automatic. – martineau Apr 15 '22 at 18:26

1 Answers1

2

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}')
martineau
  • 119,623
  • 25
  • 170
  • 301
  • Exactly what I need. I added a line `os.path.basename(caller_path)` to only get the file name and not full path but that worked great. Thank you – 0blex Apr 16 '22 at 17:45
  • You shouldn't need to use `os.path.basename()` because the result is the same as simply using `caller_path.name` as is being done in the `print()` call in my answer. – martineau Apr 16 '22 at 18:05