How to print source code lines in python logger
Is there some relatively simpl开发者_如何学JAVAe 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:
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()
精彩评论