0

I have a very generic function widely used in my program and I want this function to write some logs specifying the file name and line number where it was called (not the useless informatino about where the logging call is).

With the code below:

# myutils.py

def track(iterator, description:str):
    logging.info("Very useful information about {description}")
    # stuff
    yield something
# main.py
import myutils

for item in myutils.track(object1, "first"):
   pass

for item in myutils.track(object2, "second"):
   pass

I would like to obtain:

main.py:4         Very useful information about first
main.py:7         Very useful information about second

but I obtain:

myutils.py:4      Very useful information about first
myutils.py:4      Very useful information about second

I understant this may not be a good practice but I would like to have the information about which file/line number is calling the track() function, not the logging.info()...

Edit: I don't want a traceback with all called functions, just a simple fix for a more useful logging.

Davis Herring
  • 36,443
  • 4
  • 48
  • 76
  • With Python 3.8 and later, you add `stacklevel=2` to your logging call. e.g. `logging.info("Something something", stacklevel=2)`. See, for example, https://stackoverflow.com/questions/49987228/alter-python-logger-stack-level – Dan Mašek May 22 '23 at 12:58
  • You can [extract your own stack trace](https://docs.python.org/3/library/traceback.html#traceback.extract_stack) and pick from it whatever you want and log it… but the built-in logging option for that seems simpler and more useful. – deceze May 22 '23 at 13:15
  • 1
    Yes! That's waht I was looking for, @Dan . I'm gonna add that, if logging with `logging.info()` (without previously getting the logging.Logger) there's an extra call inside logging's init file added to the stack so you should call `logger.info("", stacklevel=2)` or `logging.info("", stacklevel=3)` to get one stack level back. – Jordi Torrents May 22 '23 at 13:21

0 Answers0