0

I am trying to create logs for errors. This is the logger i am using.

import logging
import os

def create_log(source):
    logging.basicConfig(filename="logs/"+source+".log",
                        format='%(asctime)s::%(levelname)s::%(message)s',
                        filemode='a')
logger = logging.getLogger()
logger.setLevel(logging.INFO)

def info_logger(message):
    logger.info(message)

def error_logger(message):
    print(message)
    logger.error(message)

I am calling this logger in a for loop where i am doing some operation and trying to create logs for each iteration

for i in data["source_id"]:
   
   --Some task here--

   log_file_name = str(source_dict["source_id"]) + "_" + source_dict["source_name"] + "_"+str(datetime.today().strftime("%Y-%m-%d_%H_%M_%S"))
   
   create_log(log_file_name)

for the first iteration, log file is getting created. But for other iterations, the same log file is getting appended. I want to make seperate log files for each iteration. Any idea how can i do that?

Krawly
  • 67
  • 6

1 Answers1

0

You can try this

import logging

debug = logging.FileHandler("debug.log")
debug.setLevel(logging.DEBUG)

error = logging.FileHandler("error.log")
error.setLevel(logging.ERROR)

warning = logging.FileHandler("warning.log")
warning.setLevel(logging.WARNING)

console = logging.StreamHandler()

logging.basicConfig(  # noqa
    level=logging.INFO,
    format="[%(asctime)s]:%(levelname)s %(name)s :%(module)s/%(funcName)s,%(lineno)d: %(message)s",
    handlers=[debug, error, warning, console]
)

logger = logging.getLogger()
logger.debug("This is debug  [error+warning]")
logger.error("This is error  [error only]")
logger.warning("This is warn [error+warning]")

ozcanyarimdunya
  • 2,324
  • 1
  • 18
  • 21
  • as the project is quite big and the logger is used in multiple files, it would be difficult to make changes for now. Is there any way to close the logger after every loop? – Krawly Jun 14 '21 at 09:48