1

Is there a way to log messages as if they originated from the current function's caller?

I have a very simple global logging facility that gets initialized by means of __main__ as

logformat = '%(asctime)s %(levelname)s %(module)s:%(funcName)s:%(lineno)d - %(message)s' logging.basicConfig(format=logformat, level=loglevel) 

All functions then use the same global logger directly by means of

# Goes directly to the global logger logging.warning('this might not work') 

Some utility functions emit logs, but it is rather unhelpful that %(module)s:%(funcName)s:%(lineno)d resolves to helpers:my_helper_fn:42, while the caller of my_helper_fn that triggered the log is the interesting part.

Is there a way to log messages inside my_helper_fn so that funcName and friends automatically resolve to the caller of my_helper_fn? Ideally, I'd decorate my_helper_fn with something to the tune of @logAsCaller...

There is logger.findCaller which seems to be purposefully designed for this, I can't deduce from the docs how it's supposed to be used, though.

1

1 Answer 1

2

There is logger.findCaller which seems to be purposefully designed for this, I can't deduce from the docs how it's supposed to be used, though.

More or less. This is indeed the way a logger finds the caller it should use in its message, but user code has no access to this method.

But the doc for logger.debug describes the stacklevel keyword only parameter (emphasize mine):

...The third optional keyword argument is stacklevel, which defaults to 1. If greater than 1, the corresponding number of stack frames are skipped when computing the line number and function name set in the LogRecord created for the logging event. This can be used in logging helpers so that the function name, filename and line number recorded are not the information for the helper function/method, but rather its caller.

And the doc for all other logging methods says that they support the same parameters as debug.

So you could just use:

# Goes directly to the global logger logging.warning('this might not work', stacklevel=2) 
Sign up to request clarification or add additional context in comments.

1 Comment

Dang! I was under the impression I needed to subclass Logger... this logs as helper_fn instead of bar, though.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.