[Python] python logging dry add class property on method

Discussão em 'Python' iniciado por Stack, Julho 22, 2025.

  1. Stack

    Stack Membro Participativo

    Wondering what's best way to add to log informations a property of the class which the method is invoked:

    import logging
    logger = logging.getLogger()
    logger.setLevel(logging.INFO)

    handler = logging.StreamHandler() # console output
    formatter = logging.Formatter(
    "%(levelname)-8s | %(lineno)4d | %(funcName)-20s | %(message)s"
    )

    class DeviceLoggerAdapter(logging.LoggerAdapter):
    def process(self, msg, kwargs):
    kwargs["extra"] = kwargs.get("extra", {})
    kwargs["extra"]["device_name"] = self.extra["device_name"]
    return msg, kwargs

    class MyClass:

    def __init__(self, mac: str, name: str = "", model: str = ""):
    self.name = name
    self._logger = DeviceLoggerAdapter(logger, {"device_name": name})

    def method(self):
    logger.info("like to see self.name here instead adding it every time+ my text from this method")


    MyObject = MyClass()
    MyObject.name = "Gigi"
    MyObject.method()


    I've tried with logger adapter but self.name is still missing.

    Continue reading...

Compartilhe esta Página