470,648 Members | 1,547 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 470,648 developers. It's quick & easy.

Logging with callers filename and line number

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



Jul 18 '05 #1
0 1524

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

reply views Thread by Marek Augustyn | last post: by
2 posts views Thread by Tor Erik Sønvisen | last post: by
10 posts views Thread by Thomas Heller | last post: by
7 posts views Thread by Leo Breebaart | last post: by
7 posts views Thread by flupke | last post: by
12 posts views Thread by Tekkaman | last post: by
3 posts views Thread by seb | last post: by
1 post views Thread by Korara | last post: by
reply views Thread by warner | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.