Logging: set default values for custom keys in custom formatters OR choose formatter based on logger

239 views
Skip to first unread message

M T

unread,
Apr 10, 2022, 12:53:31 PM4/10/22
to django...@googlegroups.com
Hi all,

I'm trying to extend the formatter for console logging with custom keys. But I've run into two problems while doing that:

1) Root log messages of course don't provide these custom keys in their extra dict, so they throw errors. Looking at the official Python documentation, it is possible to specify defaults for a formatter (https://docs.python.org/3/library/logging.html#logging.Formatter), but Django doesn't support such a thing when trying to set it via the settings.py (as in: the formatters entry in the LOGGING specification in the settings.py doesn't support this).

2) So I looked into using that formatter only for my own log messages, for which I can control the extra dict passed to them. But it doesn't seem to be possible to provide two formatters for a single handler (kinda makes sense, since at that point, how would the handler choose the formatter?) But if I specify two different handlers of type logging.StreamHandler, only one of them seems to work (and the other handler's messages just aren't visible in the console output).

Does anyone have a solution for this?

If not, do people think it's worth requesting support for the defaults field for formatters specified in the settings.py LOGGING configuration?

Thanks!
-M

Derek

unread,
Apr 12, 2022, 2:01:26 AM4/12/22
to Django users
Re issue (1):

https://github.com/django/django/blob/main/django/utils/log.py#L31 shows how Django uses its own JSON format in  `settings.py` to set a link to its (local) own custom class `ServerFormatter`, which in turn inherits from Python's logging.Formatter. So it should be possible to create your own formatter class and reference it in the same kind of way.

(As an aside: you can do really interesting things with a customer formatter e.g. see https://alexandra-zaharia.github.io/posts/make-your-own-custom-color-formatter-with-python-logging/)

I don't understand what you're trying to achieve in (2), so cannot comment.
Reply all
Reply to author
Forward
0 new messages