-
Notifications
You must be signed in to change notification settings - Fork 32
Standardize Python Log Exporter JSON output to match canonical schema #715
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Miqueasher
wants to merge
10
commits into
main
Choose a base branch
from
standardize-compact-console-log-exporter
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
ee78b0f
Standardize Python CompactConsoleLogRecordExporter JSON output to mat…
Miqueasher 54ebc76
Merge branch 'main' into standardize-compact-console-log-exporter
Miqueasher 8baa903
fix for failing Python PR build
Miqueasher bcbc470
Merge branch 'main' into standardize-compact-console-log-exporter
Miqueasher 74bdd9b
Addressing comments
Miqueasher 1d7d4af
Adding Changelog entry
Miqueasher e81662e
Merge branch 'main' into standardize-compact-console-log-exporter
Miqueasher 77dd81a
fixing linter and test coverage failure
Miqueasher 2c7b29b
fixing lint error
Miqueasher 0db8e94
Merge branch 'main' into standardize-compact-console-log-exporter
Miqueasher File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
126 changes: 118 additions & 8 deletions
126
...tro/src/amazon/opentelemetry/distro/exporter/console/logs/compact_console_log_exporter.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,16 +1,126 @@ | ||
| # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
| # SPDX-License-Identifier: Apache-2.0 | ||
| import json | ||
| import logging | ||
| import re | ||
| from typing import Sequence | ||
| import sys | ||
| from typing import IO, Sequence | ||
|
|
||
| from opentelemetry.sdk._logs import ReadableLogRecord | ||
| from opentelemetry.sdk._logs.export import ConsoleLogRecordExporter, LogRecordExportResult | ||
| try: | ||
| from opentelemetry.sdk._logs.export import LogRecordExportResult as LogExportResult | ||
| except ImportError: | ||
| from opentelemetry.sdk._logs.export import LogExportResult | ||
|
|
||
| # Support both old (LogData/LogExporter) and new (ReadableLogRecord/LogRecordExporter) APIs | ||
| try: | ||
| from opentelemetry.sdk._logs.export import LogRecordExporter | ||
|
|
||
| _BASE_CLASS = LogRecordExporter | ||
| except ImportError: | ||
| from opentelemetry.sdk._logs.export import LogExporter | ||
|
|
||
| _BASE_CLASS = LogExporter | ||
|
|
||
| _logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| def _preserve_attrs(attributes) -> dict: | ||
| """Preserve attribute value types (int, float, bool, str, list).""" | ||
| if not attributes: | ||
| return {} | ||
| return dict(attributes) | ||
|
|
||
|
|
||
| def _get_dropped_attrs(data, record) -> int: | ||
| """Extract dropped attributes count from whichever object has it.""" | ||
| if hasattr(data, "dropped_attributes"): | ||
| return data.dropped_attributes or 0 | ||
| if hasattr(record, "dropped_attributes"): | ||
| return record.dropped_attributes or 0 | ||
| return 0 | ||
|
|
||
|
|
||
| class CompactConsoleLogRecordExporter(_BASE_CLASS): | ||
| """Exports log records as compact JSON to stdout. | ||
|
|
||
| Produces a single-line JSON object per log record aligned with the | ||
| CloudWatch OTLP backend's flattened JSON format. | ||
|
|
||
| If the standardized serialization fails for any reason, falls back to | ||
| the upstream SDK's to_json() format to avoid breaking existing infrastructure. | ||
| """ | ||
|
|
||
| def __init__(self, out: IO = None): | ||
| self._out = out or sys.stdout | ||
| self._shutdown = False | ||
|
|
||
| def export(self, batch: Sequence) -> LogExportResult: | ||
| if self._shutdown: | ||
| return LogExportResult.FAILURE | ||
|
|
||
| class CompactConsoleLogRecordExporter(ConsoleLogRecordExporter): | ||
| def export(self, batch: Sequence[ReadableLogRecord]): | ||
| for data in batch: | ||
| formatted_json = self.formatter(data.log_record) | ||
| print(re.sub(r"\s*([{}[\]:,])\s*", r"\1", formatted_json), flush=True) | ||
| try: | ||
| line = self._to_compact_json(data) | ||
| except Exception: # pylint: disable=broad-exception-caught | ||
| _logger.debug( | ||
| "Failed to serialize log record, falling back", | ||
| exc_info=True, | ||
| ) | ||
| try: | ||
| line = self._fallback_format(data) | ||
| except Exception: # pylint: disable=broad-exception-caught | ||
| _logger.debug("Fallback also failed", exc_info=True) | ||
| continue | ||
|
|
||
| self._out.write(line + "\n") | ||
| self._out.flush() | ||
|
|
||
| return LogExportResult.SUCCESS | ||
|
|
||
| def shutdown(self): | ||
| self._shutdown = True | ||
|
|
||
| @staticmethod | ||
| def _to_compact_json(data) -> str: | ||
| # Support both ReadableLogRecord (1.39+) and LogData (older) APIs. | ||
| record = data.log_record | ||
| resource = getattr(data, "resource", None) or getattr(record, "resource", None) | ||
| scope = getattr(data, "instrumentation_scope", None) | ||
|
|
||
| trace_id = getattr(record, "trace_id", None) | ||
| span_id = getattr(record, "span_id", None) | ||
| is_valid = trace_id is not None and span_id is not None and trace_id != 0 and span_id != 0 | ||
|
|
||
| return json.dumps( | ||
| { | ||
| "resource": { | ||
| "attributes": _preserve_attrs(resource.attributes if resource else None), | ||
| "schemaUrl": getattr(resource, "schema_url", "") or "" if resource else "", | ||
| }, | ||
| "scope": { | ||
| "name": getattr(scope, "name", "") or "" if scope else "", | ||
| "version": getattr(scope, "version", "") or "" if scope else "", | ||
| "schemaUrl": getattr(scope, "schema_url", "") or "" if scope else "", | ||
| }, | ||
| "body": record.body if record.body is not None else None, | ||
| "severityNumber": (record.severity_number.value if record.severity_number is not None else 0), | ||
| "severityText": (record.severity_number.name if record.severity_number is not None else "UNSPECIFIED"), | ||
| "attributes": _preserve_attrs(record.attributes), | ||
| "droppedAttributes": _get_dropped_attrs(data, record), | ||
| "timeUnixNano": record.timestamp or 0, | ||
| "observedTimeUnixNano": (record.observed_timestamp or 0), | ||
| "traceId": format(trace_id, "032x") if is_valid else "", | ||
| "spanId": format(span_id, "016x") if is_valid else "", | ||
| "flags": int(record.trace_flags) if record.trace_flags is not None else 0, | ||
| "exportPath": "console", | ||
| }, | ||
| separators=(",", ":"), | ||
| ) | ||
|
|
||
| return LogRecordExportResult.SUCCESS | ||
| @staticmethod | ||
| def _fallback_format(data) -> str: | ||
| """Fall back to upstream SDK's to_json() with whitespace stripped.""" | ||
| # ReadableLogRecord has to_json() directly; LogData has it on .log_record | ||
| obj = data if hasattr(data, "to_json") else data.log_record | ||
| formatted_json = obj.to_json() | ||
| return re.sub(r"\s*([{}[\]:,])\s*", r"\1", formatted_json) | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Low priority (pre-existing): fallback regex can corrupt JSON string values. The regex operates on raw JSON text without distinguishing structural characters from those inside string values. A log body containing colons, brackets, or commas would have surrounding whitespace stripped. Since this preserves pre-existing behavior and is now only in the fallback path, this is low priority but worth noting for future cleanup.