单日志行

分享于2022年07月17日 open-telemetry python 问答
【问题标题】:单日志行(Single log line)
【发布时间】:2022-07-13 22:54:58
【问题描述】:

作为开发人员,我想要一个带有 OpenTelemetry Logs 的日志行。使用以下示例,我可以使用 Otel _logs ,但它们会在多行上发出,这使得关联变得困难。

common.py

import logging

from opentelemetry.sdk._logs import (
    LogEmitterProvider,
    LoggingHandler,
    set_log_emitter_provider,
)
from opentelemetry.sdk._logs.export import BatchLogProcessor, ConsoleLogExporter
from opentelemetry.sdk.resources import Resource
from opentelemetry.semconv.resource import ResourceAttributes

from local_machine_resource_detector import LocalMachineResourceDetector


def configure_logger(name, version):
    local_resource = LocalMachineResourceDetector().detect()
    resource = local_resource.merge(
        Resource.create(
            {
                ResourceAttributes.SERVICE_NAME: name,
                ResourceAttributes.SERVICE_VERSION: version,
            }
        )
    )
    provider = LogEmitterProvider(resource=resource)
    set_log_emitter_provider(provider)
    exporter = ConsoleLogExporter()
    provider.add_log_processor(BatchLogProcessor(exporter))
    logger = logging.getLogger(name)
    logger.setLevel(logging.DEBUG)
    handler = LoggingHandler()
    logger.addHandler(handler)
    return logger

common_runner.py

from common import configure_logger

logger = configure_logger("common_runner", "6.6.6")

logger.debug(
    "common_runner.py module has been run",
    extra={
        "username": "Sid Vicous",
    },
)

这是输出:

{
    "body": "common_runner.py module has been run",
    "severity_number": "",
    "severity_text": "DEBUG",
    "attributes": {
        "username": "Sid Vicous"
    },
    "timestamp": "2022-07-13T14:40:08.595698Z",
    "trace_id": "0x00000000000000000000000000000000",
    "span_id": "0x0000000000000000",
    "trace_flags": 0,
    "resource": "BoundedAttributes({'telemetry.sdk.language': 'python', 'telemetry.sdk.name': 'opentelemetry', 'telemetry.sdk.version': '1.11.1', 'net.host.name': 'Doug.Ramirez', 'net.host.ip': '127.0.0.1', 'service.name': 'common_runner', 'service.version': '6.6.6'}, maxlen=None)"
}

这是我希望在我的 APM 平台 (Datadog) 中看到的内容:

{"body": "common_runner.py module has been run", "severity_number": "", "severity_text": "DEBUG", "attributes": {"username": "Sid Vicous"}, "timestamp": "2022-07-13T14:40:08.595698Z",    "trace_id": "0x00000000000000000000000000000000", "span_id": "0x0000000000000000", "trace_flags": 0,    "resource": "BoundedAttributes({'telemetry.sdk.language': 'python', 'telemetry.sdk.name': 'opentelemetry', 'telemetry.sdk.version': '1.11.1', 'net.host.name': 'Doug.Ramirez', 'net.host.ip': '127.0.0.1', 'service.name': 'common_runner', 'service.version': '6.6.6'}, maxlen=None)"}


【解决方案1】:

您可以将 stringifying replacing 组合使用您的日志,就像这样!

log_as_str = str(log)
print(log_as_str.replace("\n", ""))

如果您的日志是 dict() ,它应该可以正常工作。以防万一,您可以使用 json.dumps(log)

  • 感谢您的回复。不幸的是,这并没有解决 OpenTelemetry Logging 的特定用例。