Aug-16-2020, 02:33 PM
Hi,
I am trying to generate a sperate log file on each iteration using below-shown code, although I use file mode "w", and it is generating a separate log file on each iteration but first file is appending all three iterations log, and the second file is appending 2~3 iteration log, and the third log only have the third iteration log. But I I want a log file contain only that iteration log. How to close file handler or log file on eah iteration.
I am trying to generate a sperate log file on each iteration using below-shown code, although I use file mode "w", and it is generating a separate log file on each iteration but first file is appending all three iterations log, and the second file is appending 2~3 iteration log, and the third log only have the third iteration log. But I I want a log file contain only that iteration log. How to close file handler or log file on eah iteration.
import logging
targets = ["a", "b", "c"]
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
for target in targets:
log_file = "{}.log".format(target)
log_format = "|%(levelname)s| : [%(filename)s]--[%(funcName)s] : %(message)s"
formatter = logging.Formatter(log_format)
file_handler = logging.FileHandler(log_file, mode='w')
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
logger.info("Log file: {}".format(target))
logger.info("Hello")I am getting the below output now,a.log |INFO| : [loggingloger.py]--[<module>] : Log file: a |INFO| : [loggingloger.py]--[<module>] : Hello |INFO| : [loggingloger.py]--[<module>] : Log file: b |INFO| : [loggingloger.py]--[<module>] : Hello |INFO| : [loggingloger.py]--[<module>] : Log file: c |INFO| : [loggingloger.py]--[<module>] : Hello b.og: |INFO| : [loggingloger.py]--[<module>] : Log file: b |INFO| : [loggingloger.py]--[<module>] : Hello |INFO| : [loggingloger.py]--[<module>] : Log file: c |INFO| : [loggingloger.py]--[<module>] : Hello c.log |INFO| : [loggingloger.py]--[<module>] : Log file: c |INFO| : [loggingloger.py]--[<module>] : Hello
