Logging with callers filename and line number

Tero Saarni terosaarni at hotmail.com
Mon Mar 22 15:10:37 EST 2004


I'm using Logging in my library module for producing trace log of
certain events.

For being more useful these log entries should be associated with the 
filename and line number of *users* code that was issuing the library
call.  This is similar to what Logging itself does since it doesn't
print "logging/__init__.py" as value of %(filename) but instead it
prints users file where logging method (info, error...) was called.

What would be the best way to achieve this also for other modules?


I took a quick look into the code in Logging module to see if it
provides means for controlling what goes into %(filename) and %(lineno)
but I didn't find any. I then ended up in subclassing Logger and
redefining Logger.findCaller() to skip a list of files instead of just
one file. Then in my library module I can add current file name into
the list of file names which logger will skip.

Does this seem like sensible solution for you:


import logging
import sys
import os

srcfilelist = [ logging._srcfile, os.path.normcase(__file__) ]

class MyLogger(logging.Logger):

     def findCaller(self):
         f = sys._getframe(1)
         while 1:
             co = f.f_code
             filename = os.path.normcase(co.co_filename)
             if filename in srcfilelist:
                 f = f.f_back
                 continue
             return filename, f.f_lineno

logging.setLoggerClass(MyLogger)



---
Tero




More information about the Python-list mailing list