I'm trying to write to a separate log file which is created inside a loop using basicConfig. So far I managed to create only one log file which has all the subsequent logging calls. Am I missing something trivial here? I checked the docs it had hints about filemode but nothing else.
import logging
class MultipleInstancesStarter:
def __init__(self):
pass
def startMany(self):
objs = [Main(str(i)) for i in xrange(1, 10)]
print objs
for obj in objs:
obj._start()
class Main:
def __init__(self, i):
self.index = i
def _start(self):
name = self.index
logging.basicConfig(
filename="log_" + name + ".log",
filemode="w",
format="%(asctime)s - %(levelname)s - %(filename)s:%(module)s:%(lineno)d - %(message)s",
level=logging.DEBUG)
logging.debug("%s Message Debug" % name)
logging.info("%s Message Info" % name)
logging.error("%s Message Error" % name)
if __name__ == '__main__':
MultipleInstancesStarter().startMany()
This creates only log_1.log with log entries from 2nd iteration as well. I tried creating an object outside the loop and it creates a separate file no problem though as shown below.
def startMany(self):
obj2 = Main("sample")
obj2._start()
objs = [Main(str(i)) for i in xrange(1, 10)]
print objs
for obj in objs:
obj._start()
Not sure what I'm doing wrong though, any help would be appreciated. Cheers
print objs?This function does nothing if the root logger already has handlers configured for it.. You probably need to calllogging.shutdownafter your logging to a file is done, in order to flush the handlers and allow logging to be reconfigured with an other file.logging.shutdown()as the last line of_start)