#🔒 How Handle Potential ContextVar Access Outside Of Context

4 messages · Page 1 of 1 (latest)

fresh stratus
#
ctx_correlation_id = ContextVar("correlation_id", default="")

@contextmanager
def set_correlation_id(existing_id: str | None = None) -> Iterator[str]:
    """Within this context logging includes correlation id."""
    correlation_id = existing_id or str(uuid.uuid4())
    token = ctx_correlation_id.set(correlation_id)
    try:
        yield correlation_id
    finally:
        ctx_correlation_id.reset(token)


def get_correlation_id() -> str:
    """Get the current correlation ID from context."""
    return ctx_correlation_id.get()


class CorrelationIdFilter(logging.Filter):
    """Filter that injects correlation id for logging."""

    def filter(self, record: logging.LogRecord) -> bool:
        """Add `correlation_id` to logging record."""
        record.correlation_id = ctx_correlation_id.get()
        return True

I'm using get_correlation_id within the context, but it's not always clearly visible that it's within -> what are your thoughts on that wrong approach or acceptable & just throw an error when correlation id is not set?

covert hillBOT
#

@fresh stratus

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

covert hillBOT
#

@fresh stratus

Python help channel closed for inactivity

This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.