Skip to content

Add optional default_extra param to formatter initializer. #12

New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from

Conversation

matteo-zanoni
Copy link

This is used to specify extra parameters that are valid for all log messages formatted with the formatter. It is usefull to avoid repeting extra={...} in every log call.

Closes #11

This is used to specify extra parameters that are valid for all log
messages formatted with the formatter. It is usefull to avoid repeting
`extra={...}` in every log call.
@josheppinette
Copy link
Owner

@matteo-zanoni thank you for your pr. I will test it today, also I will update with tests and documentation before merge.

@matteo-zanoni
Copy link
Author

@jteppinette happy to help with any of those tasks... Just looking for some guidance I guess

The _old_ way described in the docs is now deprecated since the
`default_extra` parameter achieves the same outcome in a more clean and
explicit way.
@matteo-zanoni
Copy link
Author

@jteppinette I have updated the documentation and added simple tests for the new behaviour. Hoping this can be helpful

@matteo-zanoni
Copy link
Author

Hi @jteppinette have you been able to review this PR? Can I help with anything to get this merged and released?

@tapetersen
Copy link
Contributor

tapetersen commented Jan 24, 2025

Disclaimer: I'm not a maintainer so feel free to disregard

If I understand the use-case correctly here (adding some extra fields to the log-record that are outputted for all records that are formatted)

For cases like this (modifying all records or at least a subset) using adapters or filters
are often a more generally useful pattern than putting it into the formatter directly.

For this usecase for example a simple filter on the handler or in the logger-chain before that can accomplish the same thing without adding complexity to the formatter (which also means it works with all other handlers/formatters).

import logging
def add_extra_attrs(record: logging.Record):
    if not hasattr(record, "foo"):
        record.foo = "bar"
    return True # To continue the logging chain and not drop the record

# Add to root logger for all records
logging.root.addFilter(add_extra_attr)

# Or just to a specific handler
file_handler = logging.FileHandler("log.txt")
file_handler.addFilter(add_extra_attrs)

# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Enhancement: include extra fields in formatter
3 participants