Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python logging is not creating multiple instance of log files

I am trying to create a class that can create multiple instances of logging with saved .log.

This is my code:

import logging
from datetime import datetime
import sys
import os


class DummyLog:
    def __init__(self,
                 log_name: str = datetime.now().strftime('%d_%m_%Y__%H_%M_%S'),
                 logging_level: str = 'debug',
                 string_format: str = '%(asctime)s: %(levelname)s: %(message)s',
                 datetime_format: str = '%m/%d/%Y %I:%M:%S %p',
                 log_on_folder: bool = True,
                 log_folder_name: str = 'logs'
                 ):
        self.logName = log_name
        self.logger = None
        self.loggingLevel = logging_level
        self.stringFormat = string_format
        self.datetimeFormat = datetime_format

        if log_on_folder:
            if not os.path.exists(log_folder_name):
                os.mkdir(log_folder_name)
            self.logName = log_folder_name + '/' + self.logName

        self.initiateLogger()

    def initiateLogger(self):
        """ This function will initiate the logger as a single threaded log"""

        self.logger = logging.getLogger(self.logName)
        if self.loggingLevel == 'debug':
            self.loggingLevel = logging.DEBUG
        self.logger.setLevel(self.loggingLevel)
        logFormat = logging.Formatter(self.stringFormat, datefmt=self.datetimeFormat)

        # Creating and adding the console handler
        consoleHandler = logging.StreamHandler(sys.stdout)
        consoleHandler.setFormatter(logFormat)
        self.logger.addHandler(consoleHandler)

        # Creating and adding the file handler
        fileHandler = logging.FileHandler(self.logName + ".log", mode='w')
        fileHandler.setFormatter(logFormat)
        self.logger.addHandler(fileHandler)


dl = DummyLog()
dl.logger.info("hi")

import time
time.sleep(1)

dl1 = DummyLog()
dl1.logger.info("hi")

When I run the above code, it creates only one .log file and both the dl and dl1 objects are being logged on the same .log file.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The console output is printing the log 3 times instead of 2 times:

01/03/2022 12:01:20 PM: INFO: hi
01/03/2022 12:01:21 PM: INFO: hi
01/03/2022 12:01:21 PM: INFO: hi

but I have initiated the class Dummylog two times. I am expecting the code change where the class DummyLog can be called at multiple instances and each instance will save an individual .log file.

I know I am missing something in the Handler, but nothing is helping me to come over the required change.

Any help will be appreciated !!

>Solution :

Your default log name is based on time, but accuracy is second you must put sleep between logger instance or use non-default names:

dl = DummyLog(log_name="name1.txt")
dl.logger.info("hi")

import time
time.sleep(1)

dl1 = DummyLog(log_name="name2.txt")
dl1.logger.info("hi")

and result will be

logs
├── name1.txt.log
└── name2.txt.log
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading