代码之家  ›  专栏  ›  技术社区  ›  Maarten Ureel

从自定义处理程序中的LoggerAdapter访问额外变量

  •  0
  • Maarten Ureel  · 技术社区  · 4 年前

    我有一个自定义的LoggingAdapter,我向它传递了一个call_id变量。

    # The adapter itself
    class FreeSWITCHLoggingAdapter(logging.LoggerAdapter):
        def process(self, msg, kwargs):
            return "[%s] %s" % (self.extra["call_id"], msg), kwargs
    
    # And this is how we initialize it
    logger = FreeSWITCHLoggingAdapter(
        logging.getLogger(__name__), {"call_id": "some context specific ID here"}
    )
    logger.info("something related to a call")
    

    在日志记录器上,我还添加了一个自定义处理程序,需要访问该call_id。

    class FreeSWITCHLoggingHandler(logging.Handler):
        def emit(self, record):
            msg = self.format(record)
    
            # How can I access extra or call_id here?
    
    0 回复  |  直到 4 年前
        1
  •  1
  •   Maarten Ureel    4 年前

    我通过浏览LoggerAdapter本身的源代码找到了答案。

    LoggerAdapter定义了一个流程方法:

    def process(self, msg, kwargs):
        kwargs["extra"] = self.extra
        return msg, kwargs
    

    这基本上使数据在记录中可用。所以我真的不需要自己的类,我只是使用了默认的适配器:

    logger = logging.LoggerAdapter(
        root_logger, {"call_id": session.getVariable("uuid")}
    )
    

    通过这种方式,我设法将Python的内置日志记录与FreeSWITCH的细节联系起来:

    class FreeSWITCHLoggingHandler(logging.Handler):
        # Map Python log levels to FreeSWITCH log levels
        FS_LOG_LEVEL_MAP {
            "CRITICAL": "crit",
            "ERROR": "err",
            "WARNING": "warning",
            "INFO": "info",
            "DEBUG": "debug",
            "NOTSET": "console"
        }
    
        def emit(self, record):
            msg = self.format(record)
    
            # Map to a FreeSWITCH log level
            fs_log_level = FS_LOG_LEVEL_MAP[record.levelname]
    
            if hasattr(record, "call_id"):
                consoleLog(fs_log_level, "[%s] %s" % (record.call_id, str(msg)) + "\n")
            else:
                consoleLog(fs_log_level, str(msg) + "\n")
    

    如您所见 record.call_id 现在可用。