#๐Ÿ”’ Contextual Logging Hell? - ContextVar

6 messages ยท Page 1 of 1 (latest)

light violetBOT
#

@royal flicker

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.

royal flicker
#
ctx_correlation_id = ContextVar("correlation_id", default="")


class InjectingFilter(logging.Filter):
    def __init__(self, app: Any):
        self.app = app

    def filter(self, record: Any):
        record.correlation_id = ctx_correlation_id.get()
        return True


class LoggingFW:
    """
    LoggingFW sets up logging using OpenTelemetry with a specified service name and instance ID.
    """

    def __init__(self, service_name: str):
        """
        Initialize the LoggingFW with a service name and instance ID.

        :param service_name: Name of the service for logging purposes.
        """
        # Create an instance of LoggerProvider with a Resource object that includes
        # service name and instance ID, identifying the source of the logs.
        self.logger_provider: LoggerProvider = LoggerProvider(
            resource=Resource.create(
                {
                    "service.name": service_name,
                }
            )
        )
#
def setup_logging(self):
        """
        Set up the logging configuration.

        :return: LoggingHandler instance configured with the logger provider.
        """
        # Set the created LoggerProvider as the global logger provider.
        set_logger_provider(self.logger_provider)

        # Create an instance of OTLPLogExporter with insecure connection.
        exporter = OTLPLogExporter(endpoint="localhost:4317", insecure=True)

        # Add a BatchLogRecordProcessor to the logger provider with the exporter.
        self.logger_provider.add_log_record_processor(BatchLogRecordProcessor(exporter))

        # Create a LoggingHandler with the specified logger provider and log level set to NOTSET.
        handler = LoggingHandler(
            level=logging.NOTSET, logger_provider=self.logger_provider
        )

        formatter = logging.Formatter(
            "[%(correlation_id)s] [%(name)s] %(levelname)s ::: %(message)s"
        )
        handler.setFormatter(formatter)

        f = InjectingFilter(self)
        handler.addFilter(f)

        return handler
royal flicker
#

Resolved! ๐Ÿ™‚

light violetBOT
#
Python help channel closed using Discord native close action

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.