[Django]-Elegant rotating logging filename in django

5👍

You forgot 'when': 'midnight', and possibly a wrapper if you log from multiple instances. Try this:

LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
    'require_debug_false': {
        '()': 'django.utils.log.RequireDebugFalse'
    }
},
'formatters': {
    'verbose': {
        'format': '%(levelname)s|%(asctime)s|%(module)s|%(process)d|%(thread)d|%(message)s',
        'datefmt' : "%d/%b/%Y %H:%M:%S"
    },
},
'handlers': {
    'default': {
        'level': 'INFO',
        'class': 'logging.handlers.TimedRotatingFileHandler',
        'filename': os.path.join(ROOT_DIR, 'django.log'),
        'formatter': 'verbose',
        'when': 'midnight',
        'backupCount': '30',
    },
},
'loggers': {
    'sensible': {
        'handlers': ['default'],
        'level': 'DEBUG',
        'propagate': True,
    },
}

The system will save old log files by appending extensions to the
filename. The extensions are date-and-time based, using the strftime
format %Y-%m-%d_%H-%M-%S or a leading portion thereof, depending on
the rollover interval.

1👍

Django logging is just a thin wrapper of the Python logging module, you can use that to override Django settings if needed.

Rotating logs in Python:

import logging
import time

from logging.handlers import TimedRotatingFileHandler

#----------------------------------------------------------------------
def create_timed_rotating_log(path):
    """"""
    logger = logging.getLogger("Rotating Log")
    logger.setLevel(logging.INFO)

    handler = TimedRotatingFileHandler(path,
                                       when="midnight",
                                       interval=1,
                                       backupCount=5)
    logger.addHandler(handler)

    for i in range(6):
        logger.info("This is a test!")
        time.sleep(75)

#----------------------------------------------------------------------
if __name__ == "__main__":
    log_file = "timed_test.log"
    create_timed_rotating_log(log_file)

Bypassing Django might also avoid parent loggers not receiving events from disabled children.

Leave a comment