Ruben Ruben - 3 months ago 15
Python Question

Django logging: Cannot create logs per day

I'm trying to order my logs per day, however it doesnt create a new file when it is a new day. it continues storing the logs in the previous day unless I restart the server. How could I fix that?

I'm using Django 1.4.

Thanks in advance!

LOGGING = {
'version': 1,
'disable_existing_loggers': True,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'formatters':{
'verbose': {
'format': '[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s'
},
'simple': {
'format': '[%(levelname)s] %(message)s'
},
},
'handlers': {
'file_django': {
'class': 'logging.FileHandler',
'filename': '/var/log/zboss/django/log_' + date.today().strftime('%Y%m%d') + '.log',
'formatter': 'verbose',
'level': 'DEBUG'
},
'file_modules': {
'class': 'logging.FileHandler',
'filename': '/var/log/zboss/log_' + date.today().strftime('%Y%m%d') + '.log',
'formatter': 'verbose',
'level': 'DEBUG'
},
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
},
},
'loggers': {
'django': {
'handlers': ['file_django'],
'propagate': True,
'level': 'DEBUG'
},
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
'core.views': {
'handlers': ['file_modules'],
'propagate': True,
'level': 'DEBUG'
},
},
}

Answer

Don't set the date there: it'll be evaluated at import time only.

Instead, use logging.TimedRotatingFileHandler, which adds the timestamp for you automatically, like this:

LOGGING = {
    # ...
    'handlers': {
        'file': {
            'level': 'INFO',
            'formatter': 'verbose',
            'filename': os.path.join(FOOBAR, 'foobar.log'),
            'class': 'logging.handlers.TimedRotatingFileHandler',
            'when': 'midnight',
            'interval': 1,
        },
    },
}