Home > Software engineering >  Configure django logger to perform write logs to seperate file every 24hrs
Configure django logger to perform write logs to seperate file every 24hrs

Time:10-26

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.

CodePudding user response:

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',
    },

},  

CodePudding user response:

Django's logging configuration is based on the dictionary config provided by the logging module . You can use any of the handlers that the logging module provides. In this case, it would be the TimedRotatingFileHandler.

'handlers':{
    'to_file':{
        'level':'DEBUG',
        'class': 'logging.handlers.TimedRotatingFileHandler',
        'when': 'D',
        'interval': 1,
        'backupCount': 0,
        'filename':'./logs/debug.log',
        'formatter':'simpleRe',
    },
},
  • Related