By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,547 Members | 1,425 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,547 IT Pros & Developers. It's quick & easy.

Logging with callers filename and line number

P: n/a

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/" 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
return filename, f.f_lineno



Jul 18 '05 #1
Share this question for a faster answer!
Share on Google+

This discussion thread is closed

Replies have been disabled for this discussion.