Friday, April 23, 2010

Convenient thread logging in Python

I wrote a small logging thread class for easy logging.
My standard error now looks like this:
[Fri Apr 23 15:58:20 2010] [ClipboardReader-1] Starting log...
[Fri Apr 23 15:58:20 2010] [SocksValidator-1] Starting log...
[Fri Apr 23 15:58:20 2010] [SocksChecker-1] Starting log...
Every thread also has its own logfile in the "logs" directory by his class name. I made up the thread name to add the class name of the instance (won't be LoggingThread if you inherit from it).
class LoggingThread(threading.Thread):
def __init__(self, *args, **kwargs):
threading.Thread.__init__(self, *args, **kwargs)
if hasattr(self.__class__, "instance_count"):
self.__class__.instance_count += 1
else:
self.__class__.instance_count = 1

self.name = "%s-%d" % (self.__class__.__name__, self.__class__.instance_count)

if not os.path.isdir("logs"):
os.makedirs("logs")
self.logfile = open("logs/%s.log" % self.name, "w")
self.log("Starting log...")

def log(self, data):
logline = "[%s] [%s] %s" % (time.ctime(), self.name, data)
print >> self.logfile, logline
self.logfile.flush()
print >> sys.stdout, logline

No comments: