Melissa Stewart
Melissa Stewart

Reputation: 3605

Logging in django usig a custom formatter

I'm using the following logging configurations in my code.

LOGGING = {
    'version': 1,
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
            'stream': sys.stdout,
        }
    },
    'formatters': {
        'simple': {
            'format': '%(levelname)s %(asctime)s %(name)s.%(funcName)s:%(lineno)s- %(message)s'
        },
    },
    'root': {
        'handlers': ['console'],
        'level': 'INFO'
    }
}

This is how I log.

logging.config.dictConfig(LOGGING)
logging.info('Hello World!')

The issue is that the format string is not being respected. How can I get the formatter to work?

Upvotes: 2

Views: 1062

Answers (1)

Wyrmwood
Wyrmwood

Reputation: 3599

You need to tell the handler to use your formatter.

LOGGING = {
    'version': 1,
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
            'stream': sys.stdout,
            'formatter': 'simple',
        }
    },
    'formatters': {
        'simple': {
            'format': '%(levelname)s %(asctime)s %(name)s.%(funcName)s:%(lineno)s- %(message)s'
        },
    },
    'root': {
        'handlers': ['console'],
        'level': 'INFO'
    }
}

>>> logging.config.dictConfig(LOGGING)
>>> logging.info('test')
INFO 2018-12-04 10:35:29,879 root.<module>:1- test

'formatter': 'simple',

Upvotes: 3

Related Questions