python-logfmter icon indicating copy to clipboard operation
python-logfmter copied to clipboard

Add optional `default_extra` param to formatter initializer.

Open matteo-zanoni opened this issue 1 year ago • 5 comments

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

matteo-zanoni avatar Feb 02 '24 09:02 matteo-zanoni

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

josheppinette avatar Feb 02 '24 14:02 josheppinette

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

matteo-zanoni avatar Feb 02 '24 14:02 matteo-zanoni

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

matteo-zanoni avatar Mar 01 '24 13:03 matteo-zanoni

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

matteo-zanoni avatar Mar 14 '24 13:03 matteo-zanoni

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)

tapetersen avatar Jan 24 '25 10:01 tapetersen