Add param for indent size to LogRecord.to_json() by dougramirez · Pull Request #2870 · open-telemetry/opentelemetry-python
This change will allow callers to the LogRecord.to_json() func to specify an indent. Previously the func used 4 as the indent. The consequences of that hard coding meant that log records were being emitted on > 1 line.
This PR will allow callers to send None to the func, which allows the LogRecord to be emitted on a single line. This has the benefit of allowing downstream consumers to read the log as single line and index its keys for queries.
The example below shows how this can be leveraged by sending the indent level as a param to the LogRecord.to_json() func as part of a formatter to the exporter.
import time
from os import linesep
from opentelemetry.sdk._logs import (
LogEmitterProvider,
LogRecord,
get_log_emitter_provider,
set_log_emitter_provider,
)
from opentelemetry.sdk._logs.export import ConsoleLogExporter, SimpleLogProcessor
from opentelemetry.sdk.resources import Resource
def configure_log_emitter_provider(indent):
provider = LogEmitterProvider(resource=Resource.create())
set_log_emitter_provider(provider)
formatter = lambda record: LogRecord.to_json(record, indent=indent) + linesep
exporter = ConsoleLogExporter(formatter=formatter)
provider.add_log_processor(SimpleLogProcessor(exporter))
if __name__ == "__main__":
configure_log_emitter_provider(indent=None)
log_emitter = get_log_emitter_provider().get_log_emitter(
"logs.py",
"0.0.1",
)
log_record = LogRecord(
timestamp=time.time_ns(),
body="I am a log line. The one and only.",
)
log_emitter.emit(log_record)
{"body": "I am a log line. The one and only.", "severity_number": "None", "severity_text": null, "attributes": null, "timestamp": "2022-08-10T13:26:04.048569Z", "trace_id": "", "span_id": "", "trace_flags": null, "resource": ""}
Please delete options that are not relevant.
Please describe the tests that you ran to verify your changes. Provide instructions so we can reproduce. Please also list any relevant details for your test configuration