Hook on logging events to add dynamic keys? #5455
-
I have a use-case whereby I would like to append keys which have values which should be fetched/calculated dynamically. For example, something that would functionally be equivalent to: logger.append_keys(foo=lambda: some_context_var.get()) This could be a feature added to AWS PowerTools by inspecting the values for a In the meantime though, I was thinking that this could be achieved by monkey-patching the orig_info = logger.info
def info(*args, **kwargs) -> None:
kwargs["extra"] = {**kwargs.get("extra", {}, "foo": some_context_var.get()}
orig_info(*args, **kwargs)
logger.info = orig_info The problem here is that this would only ensure this is achieved on that specific logger instance. So my question really is: What function(s) would I need to patch to ensure that all (configured) logs behave similarly? I am using the |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 5 replies
-
Hi @JP-Ellis! Can you tell me a bit about the use case here? I understand that you want to get something dynamic and use it as a key/value when setting extras, but what's stopping you from dumping the contextvar directly into the from aws_lambda_powertools import Logger
from contextvars import ContextVar
request_id = ContextVar("default")
data = {"my_data_1": "1", "my_data_2": "2"}
request_id.set(data)
logger = Logger()
logger.append_keys(**request_id.get())
logger.info("test")
But if you still want to copy logger configuration, so, yeah Sorry for the super late reply. |
Beta Was this translation helpful? Give feedback.
Ok, I get the use case now, in theory you don't need
append_keys
, but you need to add keys that you can mutate during the execution of your function, but without adding too much new code. I think in this case you might have the benefit of using aCustomFormatter
and then overriding theserialize
method to add those keys dynamically. Please check if this code make sense for you