logging: local functions ==> loss of lineno
Jean-Michel Pichavant
jeanmichel at sequans.com
Thu Mar 11 05:44:22 EST 2010
Hellmut Weber wrote:
> Hi Vinay Sajip,
> I'm very glad discoverd your logging module ;-)
> (That's what I would have liked 25 years ago when I was working as a
> technical software developper!)
>
> Now I'm writing just some personal tools, I like python and want to
> use logging on a regular basis.
>
> Logging works very well giving the filename and line number of the
> point where it is called. As long as I use the loggers directly.
> BUT when I have to wrap the logger call in some other function, I
> always get file name and line number of the call of the logger inside
> the wrapping function.
>
> Is there a possibility to get this information in this situation too?
>
> TIA
>
> Hellmut
>
You have to specify the file and line number by yourself, the logging
feature can only assume that you want the line number of the logger call.
i.e.
in test.py:
import logging
import inspect
_logger = logging.getLogger(__name__)
class Foo:
def __init__(self):
self._logger = _logger
def info(self, msg):
previousFrame = inspect.currentframe().f_back
self._logger.info(msg,
extra={'custom_lineno':previousFrame.f_lineno, 'custom_filename':
previousFrame.f_code.co_filename})
if __name__ == '__main__':
_logger.handlers=[]
_logger.addHandler(logging.StreamHandler())
_logger.handlers[-1].setFormatter(logging.Formatter('file
%(custom_filename)s line %(custom_lineno)d : %(message)s'))
_logger.setLevel(logging.DEBUG)
foo = Foo()
foo.info('a foo info')
In [3]: run test.py
file test.py line 20 : a foo info
note that you cannot override the logging builtin 'lineno' key with the
extra dictionary, that is why I'm using the 'custom_lineno' key. I don't
know why the logger forbids it though, would have been nice to override
lineno without the need of adding a new key.
JM
More information about the Python-list
mailing list