Is there some relatively simple way to programmatically include source code lines to python logger report. For example...
import logging
def main():
something_is_not_right = True
logging.basicConfig(level=logging.DEBUG,
format=('%(filename)s: '
'%(levelname)s: '
'%(funcName)s(): '
'%(lineno)d:\t'
'%(message)s')
)
if something_is_not_right == True:
logging.debug('some way to get previous line of source code here?')
So that output would look like this.
example.py: DEBUG: main(): 14: if something_is_not_right == True:
Python Logger Propagate: Decides whether a log should be propagated to the logger's parent. By default, its value is True. A level: Like the log handler level, the logger level is used to filter out “less important” logs.
import inspect
import logging
import linecache
def main():
something_is_not_right = True
logging.basicConfig(level=logging.DEBUG,
format=('%(filename)s: '
'%(levelname)s: '
'%(funcName)s(): '
'%(lineno)d:\t'
'%(message)s')
)
if something_is_not_right:
logging.debug(linecache.getline(
__file__,
inspect.getlineno(inspect.currentframe())-1))
if __name__=='__main__':
main()
yields
test.py: DEBUG: main(): 18: if something_is_not_right == True:
Just because I saw unutbu try something similar, here's the code I came up with (too late to post otherwise):
import logging, sys
# From logging.py
def currentframe():
"""Return the frame object for the caller's stack frame."""
try:
raise Exception
except:
return sys.exc_traceback
f = open(__file__.rstrip('c'))
owncode = f.readlines()
f.close()
def main():
something_is_not_right = True
logging.basicConfig(level=logging.DEBUG,
format=('%(filename)s: '
'%(levelname)s: '
'%(funcName)s(): '
'%(lineno)d:\t'
'%(message)s')
)
if something_is_not_right == True:
prev = owncode[currentframe().tb_frame.f_back.f_lineno - 2]
logging.debug('previous line of source code here:\n%s' % prev)
if __name__ == '__main__':
main()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With