Duplicate log output when using Django logging module

Viewed 315

I am using the following logging snippet in my Django settings.py file. As seen in image below, all the logs are being captured twice.

The reason I kept root object as I wanted to capture logger.info() in console as well as log file

settings.py

LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
    'simple': {
        'format': '[%(asctime)s] %(levelname)s|%(name)s|%(message)s',
        'datefmt': '%Y-%m-%d %H:%M:%S',
    },
},
'handlers': {
    'applogfile': {
        'level': 'DEBUG',
        'class': 'logging.handlers.RotatingFileHandler',
        'filename': os.path.join(BASE_DIR, 'django_blend.log'),
        'backupCount': 10,
        'formatter': 'simple',
    },
    'console': {
        'level': 'DEBUG',
        'class': 'logging.StreamHandler',
        'formatter': 'simple'
    }
},
'root': { # this tells to capture logger.info() to console as well as in log file
        'handlers': ['console', 'applogfile'],
        'level': 'INFO',
    },
'loggers': {
        'django': {
            'handlers': ['applogfile', 'console'],
            'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'),
                }
        }
}

django.log

enter image description here

2 Answers

I tested your code in Django 3.2.7 if remove the root object it works fine and you also don't have the duplicate lines.

LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
    'simple': {
        'format': '[%(asctime)s] %(levelname)s|%(name)s|%(message)s',
        'datefmt': '%Y-%m-%d %H:%M:%S',
    },
},
'handlers': {
    'applogfile': {
        'level': 'DEBUG',
        'class': 'logging.handlers.RotatingFileHandler',
        'filename': os.path.join(BASE_DIR, 'django_blend.log'),
        'backupCount': 10,
        'formatter': 'simple',
    },
    'console': {
        'level': 'DEBUG',
        'class': 'logging.StreamHandler',
        'formatter': 'simple'
    }
},

'loggers': {
        'django': {
            'handlers': ['applogfile', 'console'],
            'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'),
                },

        },
       
}

Add 'propagate': False loggers.

'loggers': {
    'django': {
        'handlers': ['applogfile', 'console'],
        'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'),

        # prevent duplicate log in console
        'propagate': False,
       }
    }
Related