Python Forum

Full Version: How to close file handler or log file on each iteration
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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.


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
you keep adding handlers in the loop, without removing any handlers, so at the end you have 3 handlers
How can I create a new handler (not adding) on each iteration?

I used below syntac and its working,
logger.handlers.pop()
don't know is it correct way?
(Aug-16-2020, 02:47 PM)Mekala Wrote: [ -> ]How can I create a new handler (not adding) on each iteration?
import my_log

targets = ["a", "b", "c"]
for target in targets:
    my_log.logger.info(f"Log file: {target}")
So now hide boilerplate code as it not look nice mixed in with other code.

Or better use Loguru
from loguru import logger
logger.add("loop.log", rotation="1 week")

targets = ["a", "b", "c"]
for target in targets:
    logger.info(f"Log file: {target}")