How to print lines of source code in python log

Is there a relatively easy way to programmatically include lines of source code in a python log 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?') 

Thus, the output will look as follows.

 example.py: DEBUG: main(): 14: if something_is_not_right == True: 
+8
python debugging logging
source share
2 answers
 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() 

gives

 test.py: DEBUG: main(): 18: if something_is_not_right == True: 
+12
source share

Just because I saw unutbu try something like this, here is 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 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() 
+4
source share

Source: https://habr.com/ru/post/651064/


All Articles