I am having a problem using the logging utility in Python using the logging module from the std. lib. I have written a class SPFLogger which actually should be creating a new logger if one already does not exist. I have given the class I wrote in the end. The problem I am facing is:
I am creating 2/3 object of this class SPFLogger in 2/3 other classes of mine having different logger name and the handler they will be using. Although the logs are going in a single file which means the logging.getLogger(name) function is getting the same logger which was created earlier and not creating a new logger with new handler. Eventhough the logs are going in a single file the loggers names used are different which I am passing as an argument.
So for example if I do this first in the init method of class A:
obj1 = SPFLogger ("A", "A.log")
logger1 = obj.getLogger()
logger1.info("Message A") ----> Goes in A.log with logger name A
now class A calls class B so in the init method of class B I have:
obj2 = SPFLogger ("B", "B.log")
logger2 = obj.getLogger()
logger2.info("Message B") ----> still goes in A.log with logger name B ..
Is there something that needs to be done to handle this? Below is the code for SPFLogger class
<!--------------------------------------------------
#!/usr/bin/env python
import logging
import logging.config
class SPFLogger:
class SPFLogger:
"""
A logger instance will be generated using this class.
Author: Manish Marathe
Date Created: June 01, 2006, 15:10:36
"""
def __init__(self, logger_type, handler_name):
self.logger_type = logger_type
self.handler_name = handler_name
def getLogger(self):
from os import path
logging.basicConfig(level=logging.DEBUG, format='%(asctime)-s %(name)-10s %(levelname)-10s %(message)s', datefmt='%m/%d/%y %H:%M:%S', filename=self.handler_name, filemode='a+')
logger = logging.getLogger(self.logger_type)
if path.exists(self.handler_name):
if path.getsize(self.handler_name) == 0:
f = open(self.handler_name, 'a+')
str = "Date Time Logger Level Message\n"
str += "==========================================================================================================================\n"
f.write(str)
f.flush()
f.close()
else:
print "File does exists"
return logger
if __name__=="__main__":
spf = SPFLogger("Test", "test.log")
testLogger = spf.getLogger()
testLogger.debug("debug message")
testLogger.info("info message")
testLogger.warn("warn message")
testLogger.error("error message")
testLogger.critical("critical message")
---------------------------------------------------------------------------------------------------------------------------------------------->
--
Manish Marathe
SpikeSource, Inc.
http://developer.spikesource.com
-- http://mail.python.org/mailman/listinfo/python-list