2

I have a class inherited by many other classes. Related class have a logging method and logs some extra parameters beside the text I wish to log:

import logging
# some lines to set logger 
log = logging.getLogger('some_loger')

class SomeClass:
    def log_it(self, log_text):
        log.info(self.some_param + self.some_other_param + log_text + self.some_another_param)

And in any file that inherits SomeClass:

class MyOtherClass(SomeClass):
    def some_method(self):
        ...
        ...
        self.log_it('let me log this text') 

I also wish to log the current line number (line that calls self.log_it) so I can easily find the current logging line in the related file.

What is the best pythonic way to do this?

Mp0int
  • 18,172
  • 15
  • 83
  • 114
  • Side-note and not a direct answer to your question, you may be interested in [AOP](https://en.wikipedia.org/wiki/Aspect-oriented_programming) if you're not familiar with the concept. This style of programming is usually best exemplified with logging use cases. Also see this post if you want to read more + Python support http://stackoverflow.com/questions/12356713/aspect-oriented-programming-aop-in-python . A proof of concept: https://bitbucket.org/jsbueno/metapython/src/f48d6bd388fd/aspect.py –  Jul 24 '13 at 12:44

1 Answers1

1

You can use the inspect package to find the calling line of code.

I use this method to mark a function as deprecated and then track down the callers (in your unit tests of course). You can adjust to your logging needs.

Tattletale logging

In the file that will log (a.py):

import logging # of course you have this
import inspect

# some lines to set logger 
log = logging.getLogger('some_loger')
log.addHandler(logging.StreamHandler())

class SomeClass:
    def log_it(self, log_text):
        log.warn("DEPRECATION WARNING: {0[3]} was called from {1[3]} at line {1[2]} in {1[1]}".format(*inspect.stack()[:2]))

In the "child" file (b.py):

from a import SomeClass

class MyOtherClass(SomeClass):
    def some_method(self):
        self.log_it('let me log this text')~

b = MyOtherClass()
b.some_method()

Running b.py:

> python b.py
DEPRECATION WARNING: log_it was called from some_method at line 5 in b.py

check out inspect for details on what's in the stack.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Phil Cooper
  • 5,747
  • 1
  • 25
  • 41