1

Consider the example:

debug.py:

import logging

class log_funcname:

    def __init__(self, the_logger):
        self.the_logger = the_logger

    def __call__(self, fn):
        def simply_call(*args, **kwargs):
            self.the_logger.critical(fn.func_name)
            return fn(*args, **kwargs)
        return simply_call

logger = logging.getLogger()

formatter = logging.Formatter("%(lineno)s")
ch = logging.StreamHandler()
ch.setFormatter(formatter)
logger.addHandler(ch)

@log_funcname(logger)
def hello():
  pass

hello()

output:

$ python debug.py
10

I meant to create a function that calls the logger, passing it the line number and file name from where the execution really happened. If I wanted the example app to ouput 25 instead of 10, what should I change then?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
d33tah
  • 10,999
  • 13
  • 68
  • 158
  • Possible duplicate of http://stackoverflow.com/questions/5093075/how-can-i-log-current-line-and-stack-info-with-python but there is a solution there using ``inspect.currentframe()`` :D – sotapme Feb 15 '13 at 12:58
  • I know line numbers are somewhat central to your question, but by adding line numbers like that you make so much harder for others to test out your code. – Martijn Pieters Feb 15 '13 at 12:59
  • See also [How to use inspect to get the caller's info from callee in Python?](http://stackoverflow.com/q/3711184/222914) – Janne Karila Feb 15 '13 at 13:00
  • right, use the module `inspect` you will find everything there – User Feb 15 '13 at 13:04
  • @Martijn Pieters: why would it make it harder? – d33tah Feb 15 '13 at 13:04
  • @d33tah: Now it's just a simple copy and paste. Not everyone is a wiz with editors to remove the leading line numbers, etc. – Martijn Pieters Feb 15 '13 at 13:05
  • Oh, sorry, now I understood you're talking about code numbers in the code, not debug messages. – d33tah Feb 15 '13 at 13:12

0 Answers0