0

I am working on a Python project where I will have to print the logs and at the same time store the logs in a file. The problem that's occurring is that the logs are getting printed in the console in the preferred way where each line is being printed once but the logs are stored in the file in an invalid way where each line is printed twice in the file. I went through the solution here Python logging module is printing lines multiple times and implemented this one but this did not solve the problem. So the logging module is in a different file called logs.py and I am calling this file from other modules. Please do note that this logs.py is being called my 8 other modules and when called it should have just one instance

#logs.py

import logging
import logging.handlers

def get_name():
    with open("latestLogNames.txt") as f:
        for line in f:
            pass
        latestLog = line
    logfile_name = latestLog[:-1]
    return logfile_name

def setLogger(logfile_name):
    logger = logging.getLogger(__name__)
    if not getattr(logger, 'handler_set', None):
        logger.setLevel(logging.INFO)
        stream_handler = logging.StreamHandler()
        file_handler = logging.FileHandler(logfile_name)
        formatter = logging.Formatter('%(message)s')
        file_handler.setFormatter(formatter)
        logger.addHandler(file_handler)
        logger.addHandler(stream_handler)
        logger.setLevel(logging.INFO)
        logger.propagate = False
        logger.handler_set = True
    return logger

I am calling this from a different file like this:

logger = logs.setLogger(logs.get_name())

So instead of the print("......") I am implementing logger.info("......")

Ashish101
  • 135
  • 10
  • line does not exist outside the for loop. Your assignment should be in the place of pass. Try that first and see what happens. – cup Oct 16 '20 at 16:49
  • @cup I have already tested it out. It reads correctly the last line from the latestLogNames.txt. There is no mistake with that. Only problem is that when I call setLogger I guess somehow it is creating two instances and so two lines of the same kind are being printed in my log file. I just want it to print one of a line not two of the same line. – Ashish101 Oct 16 '20 at 17:06
  • Using a loop variable outside the scope of the loop does not always work. Do you use ithe `if __name__=="__main__'` or do you just write code in the file? If you just write code in the file, look at all the modules where this is done - you may be unknowingly calling it twice. – cup Oct 17 '20 at 05:59

0 Answers0