Skip to content

Otel

OpenTelemetry for nowplaying.

This sets up our logging stack to use OpenTelemetry.

SourceAttributeFilter

Bases: Filter

Used on the handler to ensure that some attributes are carried over to otel.

Source code in nowplaying/otel.py
class SourceAttributeFilter(logging.Filter):  # pragma: no cover
    """Used on the handler to ensure that some attributes are carried over to otel."""

    def filter(self, record) -> bool:
        record.source_name = record.name
        record.source_pathname = os.path.relpath(
            record.pathname, os.path.dirname(os.path.dirname(__file__))
        )
        record.source_lineno = record.lineno
        return True

setup_otel(otlp_enable=False)

Configure opentelemetry logging to stdout and collector.

Source code in nowplaying/otel.py
def setup_otel(otlp_enable=False):  # pragma: no cover
    """Configure opentelemetry logging to stdout and collector."""
    root = logging.getLogger()
    root.setLevel(logging.INFO)

    logger_provider = LoggerProvider(
        resource=Resource.create(
            {
                "service.name": "nowplaying",
            },
        )
    )
    set_logger_provider(logger_provider)

    console_exporter = ConsoleLogExporter(
        formatter=lambda record: _log_formatter(record)
    )
    logger_provider.add_log_record_processor(SimpleLogRecordProcessor(console_exporter))

    if otlp_enable:
        oltp_exporter = OTLPLogExporter(insecure=True)
        logger_provider.add_log_record_processor(BatchLogRecordProcessor(oltp_exporter))

    handler = LoggingHandler(level=logging.NOTSET, logger_provider=logger_provider)
    handler.addFilter(SourceAttributeFilter())

    root.addHandler(handler)

    logger = logging.getLogger(__name__)
    logger.info("Opentelemetry Configured (OTLP: %s)", otlp_enable)