Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print source code lines in python logger

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:
like image 740
ojs Avatar asked Jan 14 '11 13:01

ojs


People also ask

What is logging propagate Python?

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.


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()

yields

test.py: DEBUG: main(): 18:     if something_is_not_right == True:
like image 157
unutbu Avatar answered Sep 19 '22 17:09

unutbu


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()
like image 44
TryPyPy Avatar answered Sep 22 '22 17:09

TryPyPy