[Python] Extract the extra fields in logging call in log formatter

Discussão em 'Python' iniciado por Stack, Fevereiro 28, 2025.

  1. Stack

    Stack Membro Participativo

    I can add additional fields to my log message like so:

    logging.info("My log Message", extra={"someContext":1, "someOtherContext":2})


    which is nice, but unclear how to extract all the extra fields in my log formatter:

    def format(self, record):
    record_dict = record.__dict__.copy()
    print(record_dict)


    In the above, I can see all my extra fields in the output dict, but they are flattened into a dict with lots of other junk I don't want, for instance:

    {'name': 'root', 'msg': 'My log Message', 'args': (), 'levelname': 'INFO', 'levelno': 20, 'pathname': '.\\handler.py', 'filename': 'handler.py', 'module': 'handler', 'exc_info': None, 'exc_text': None, 'stack_info': None, 'lineno': 27, 'funcName': 'getPlan', 'created': 1575461352.0664868, 'msecs': 66.48683547973633, 'relativeCreated': 1253.0038356781006, 'thread': 15096, 'threadName': 'MainThread', 'processName': 'MainProcess', 'process': 23740, 'someContext': 1, 'someOtherContext':2}


    Is there any way of getting all my extra keys without having to know them all upfront?

    I am writing a json formatter and want to create a dict, for instance:

    justMyExtra = ?????
    to_log = {
    "message" record_dict["message"],
    **justMyExtra
    }

    Continue reading...

Compartilhe esta Página