MCPcopy Create free account
hub / github.com/hynek/structlog / PositionalArgumentsFormatter

Class PositionalArgumentsFormatter

src/structlog/stdlib.py:767–808  ·  view source on GitHub ↗

Apply stdlib-like string formatting to the ``event`` key. If the ``positional_args`` key in the event dict is set, it must contain a tuple that is used for formatting (using the ``%s`` string formatting operator) of the value from the ``event`` key. This works in the same way

Source from the content-addressed store, hash-verified

765
766
767class PositionalArgumentsFormatter:
768 """
769 Apply stdlib-like string formatting to the ``event`` key.
770
771 If the ``positional_args`` key in the event dict is set, it must
772 contain a tuple that is used for formatting (using the ``%s`` string
773 formatting operator) of the value from the ``event`` key. This works
774 in the same way as the stdlib handles arguments to the various log
775 methods: if the tuple contains only a single `dict` argument it is
776 used for keyword placeholders in the ``event`` string, otherwise it
777 will be used for positional placeholders.
778
779 ``positional_args`` is populated by `structlog.stdlib.BoundLogger` or
780 can be set manually.
781
782 The *remove_positional_args* flag can be set to `False` to keep the
783 ``positional_args`` key in the event dict; by default it will be
784 removed from the event dict after formatting a message.
785 """
786
787 def __init__(self, remove_positional_args: bool = True) -> None:
788 self.remove_positional_args = remove_positional_args
789
790 def __call__(
791 self, _: WrappedLogger, __: str, event_dict: EventDict
792 ) -> EventDict:
793 args = event_dict.get("positional_args")
794
795 # Mimic the formatting behaviour of the stdlib's logging module, which
796 # accepts both positional arguments and a single dict argument. The
797 # "single dict" check is the same one as the stdlib's logging module
798 # performs in LogRecord.__init__().
799 if args:
800 if len(args) == 1 and isinstance(args[0], dict) and args[0]:
801 args = args[0]
802
803 event_dict["event"] %= args
804
805 if self.remove_positional_args and args is not None:
806 del event_dict["positional_args"]
807
808 return event_dict
809
810
811def filter_by_level(

Callers 6

test_formats_tupleMethod · 0.90
test_formats_dictMethod · 0.90
test_nop_no_argsMethod · 0.90
recreate_defaultsFunction · 0.85

Calls

no outgoing calls

Tested by 5

test_formats_tupleMethod · 0.72
test_formats_dictMethod · 0.72
test_nop_no_argsMethod · 0.72

Used in the wild real call sites across dependent graphs

searching dependent graphs…