Home > Net >  Python - Create new log files after interval of 10 minutes
Python - Create new log files after interval of 10 minutes

Time:08-13

I want to set up a new log file after a certain interval of suppose say 10 minutes and all the logs should go in the new log file.

I am having logger.py defined like this -

import logging
import os


class Logger():
    loggers = {}
    logger = None
    def getlogger(self,name):
        file_formatter = logging.Formatter('%(asctime)s %(levelname)s [%(module)s : %(funcName)s] : %('
                                           'message)s')

        console_formatter = logging.Formatter('%(levelname)s -- %(message)s')
        print(os.getcwd())
        file_name = "src/logs/" name ".log"
        file_handler = logging.FileHandler(file_name)
        file_handler.setLevel(logging.DEBUG)
        file_handler.setFormatter(file_formatter)

        logger = logging.getLogger(name)
        logger.addHandler(file_handler)
        logger.setLevel(logging.DEBUG)
        logger.propagate = False
        self.loggers[name] = logger

        return logger


    def getCommonLogger(self):
        if self.loggers.get("dashboard_asset_logs"):
            return self.loggers.get("dashboard_asset_logs")
        else:
            self.logger = self.getlogger("dashboard_asset_logs")
        return self.logger

I am having the app.py defined like this

from src.main import logger


logger_obj = logger.Logger()
logger = logger_obj.getCommonLogger()


def log_trial():
    logger.info("----------Log - start ---------------------")


if __name__ == '__main__':
    log_trial()

I am running the code like this python -m src.main.app

Can anyone tell how can the logs go to files like dashboard_asset_logs and then another file after every interval of 10 minutes?

CodePudding user response:

What you are looking for is TimedRotatingFileHandler, for example

import logging.handlers
handler = logging.handlers.TimedRotatingFileHandler(
    filename=file_name,
    when="M",
    interval=10,
)

That handler will rotate the log file every 10 minutes.

  • Related