Delgan / loguru

Python logging made (stupidly) simple
MIT License
19.8k stars 695 forks source link

How to Access Contextualized Values Within do_something() Function? #1179

Open tstrg opened 3 months ago

tstrg commented 3 months ago

Hello,

I'm trying to understand how to read contextualized values within the do_something() function when using the logger.contextualize() method. Here is an example of my code:

from loguru import logger

task_id = "12345"

def do_something():
    # How can I access the contextualized 'task' value here?
    logger.info("Doing something")

with logger.contextualize(task=task_id):
    do_something()
    logger.info("End of task")
Delgan commented 3 months ago

The logger should not be used as a way to store / access values. It mainly meant to provide context to the logged message.

There is no way to access the contextualized value outside of the sink itself (and function such as filter).

I would advise to use contextvars directly instead.

tstrg commented 3 months ago

Thank you for your feedback.

I understand that the logger is primarily intended to provide context to logged messages rather than storing or accessing values. I'll explore using contextvars directly for managing contextual values.

Thanks again for your guidance!