pythondjangologgingerror-loggingdjango-logging

Configure django logger to perform write logs to seperate file every 24hrs


I am using basic logging functionality of django. I have configured logger as follow. What I need is , I want to create separate file every 24hrs in logs directory so that all the logs will be written in date wise log files.

LOGGING ={
    'version':1,
    'disable_existing_loggers': False,
    'formatters':{
        'simpleRe': {
            'format': '[{levelname}] [{asctime}] [{module}] {process:d} {thread:d} {message}',
            'style': '{',
        }
    },
    'handlers':{
        'to_file':{
            'level':'DEBUG',
            'class': 'logging.FileHandler',
            'filename':'./logs/debug.log',
            'formatter':'simpleRe',
        },
    },
    'loggers':{
        'django':{
            'handlers':['to_file'],
            'level':'DEBUG'
        }
    },
}

I also want file names should be something like 'debug_26102021.log' etc.


Solution

  • You can use logging.handlers.TimedRotatingFileHandler and specify handler configuration in logging.

    'handlers': {
        'file': {
            'level': 'INFO',
            'class': 'logging.handlers.TimedRotatingFileHandler',
            'filename': 'myproject.log',
            'when': 'D', # specifies the interval
            'interval': 1, # defaults to 1, only necessary for other values 
            'backupCount': 5, # how many backup file to keep, 5 days
            'formatter': 'verbose',
        },
    
    },