Skip to content

Commit

Permalink
Add missing to_json methods
Browse files Browse the repository at this point in the history
Fixes #2716
  • Loading branch information
ocelotl committed May 26, 2022
1 parent 709afdd commit 3090f94
Show file tree
Hide file tree
Showing 4 changed files with 334 additions and 93 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased](https://github.com/open-telemetry/opentelemetry-python/compare/v1.12.0rc1-0.31b0...HEAD)

- Add missing `to_json` methods
([#2722](https://github.com/open-telemetry/opentelemetry-python/pull/2722)
- Fix LogEmitterProvider.force_flush hanging randomly
([#2714](https://github.com/open-telemetry/opentelemetry-python/pull/2714))

Expand Down
115 changes: 82 additions & 33 deletions opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/point.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@
# pylint: disable=unused-import

from dataclasses import asdict, dataclass
from json import dumps
from typing import Sequence, Union
from json import dumps, loads
from typing import Optional, Sequence, Union

# This kind of import is needed to avoid Sphinx errors.
import opentelemetry.sdk.metrics._internal
Expand All @@ -36,6 +36,29 @@ class NumberDataPoint:
time_unix_nano: int
value: Union[int, float]

def to_json(self) -> str:
return dumps(asdict(self))


@dataclass(frozen=True)
class HistogramDataPoint:
"""Single data point in a timeseries that describes the time-varying scalar
value of a metric.
"""

attributes: Attributes
start_time_unix_nano: int
time_unix_nano: int
count: int
sum: Union[int, float]
bucket_counts: Sequence[int]
explicit_bounds: Sequence[float]
min: float
max: float

def to_json(self) -> str:
return dumps(asdict(self))


@dataclass(frozen=True)
class Sum:
Expand All @@ -51,9 +74,10 @@ class Sum:
def to_json(self) -> str:
return dumps(
{
"data_points": dumps(
[asdict(data_point) for data_point in self.data_points]
),
"data_points": [
loads(data_point.to_json())
for data_point in self.data_points
],
"aggregation_temporality": self.aggregation_temporality,
"is_monotonic": self.is_monotonic,
}
Expand All @@ -71,30 +95,14 @@ class Gauge:
def to_json(self) -> str:
return dumps(
{
"data_points": dumps(
[asdict(data_point) for data_point in self.data_points]
)
"data_points": [
loads(data_point.to_json())
for data_point in self.data_points
],
}
)


@dataclass(frozen=True)
class HistogramDataPoint:
"""Single data point in a timeseries that describes the time-varying scalar
value of a metric.
"""

attributes: Attributes
start_time_unix_nano: int
time_unix_nano: int
count: int
sum: Union[int, float]
bucket_counts: Sequence[int]
explicit_bounds: Sequence[float]
min: float
max: float


@dataclass(frozen=True)
class Histogram:
"""Represents the type of a metric that is calculated by aggregating as a
Expand All @@ -108,9 +116,10 @@ class Histogram:
def to_json(self) -> str:
return dumps(
{
"data_points": dumps(
[asdict(data_point) for data_point in self.data_points]
),
"data_points": [
loads(data_point.to_json())
for data_point in self.data_points
],
"aggregation_temporality": self.aggregation_temporality,
}
)
Expand All @@ -126,17 +135,17 @@ class Metric:
exported."""

name: str
description: str
unit: str
description: Optional[str]
unit: Optional[str]
data: DataT

def to_json(self) -> str:
return dumps(
{
"name": self.name,
"description": self.description if self.description else "",
"unit": self.unit if self.unit else "",
"data": self.data.to_json(),
"description": self.description or "",
"unit": self.unit or "",
"data": loads(self.data.to_json()),
}
)

Expand All @@ -149,6 +158,21 @@ class ScopeMetrics:
metrics: Sequence[Metric]
schema_url: str

def to_json(self) -> str:
return dumps(
{
"scope": {
"name": self.scope.name,
"version": self.scope.version,
"schema_url": self.scope.schema_url,
},
"metrics": [
loads(metric.to_json()) for metric in self.metrics
],
"schema_url": self.schema_url,
}
)


@dataclass(frozen=True)
class ResourceMetrics:
Expand All @@ -158,9 +182,34 @@ class ResourceMetrics:
scope_metrics: Sequence[ScopeMetrics]
schema_url: str

def to_json(self) -> str:
return dumps(
{
"resource": {
"attributes": dict(self.resource.attributes.items()),
"schema_url": self.resource.schema_url,
},
"scope_metrics": [
loads(scope_metrics.to_json())
for scope_metrics in self.scope_metrics
],
"schema_url": self.schema_url,
}
)


@dataclass(frozen=True)
class MetricsData:
"""An array of ResourceMetrics"""

resource_metrics: Sequence[ResourceMetrics]

def to_json(self) -> str:
return dumps(
{
"resource_metrics": [
loads(resource_metrics.to_json())
for resource_metrics in self.resource_metrics
]
}
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
# Copyright The OpenTelemetry Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from unittest import TestCase

from opentelemetry import metrics
from opentelemetry.sdk.metrics import MeterProvider
from opentelemetry.sdk.metrics.export import (
ConsoleMetricExporter,
PeriodicExportingMetricReader,
)


class TestConsoleExporter(TestCase):
def test_console_exporter(self):

try:
exporter = ConsoleMetricExporter()
reader = PeriodicExportingMetricReader(exporter)
provider = MeterProvider(metric_readers=[reader])
metrics.set_meter_provider(provider)
meter = metrics.get_meter(__name__)
counter = meter.create_counter("test")
counter.add(1)
except Exception as error:
self.fail(f"Unexpected exception {error} raised")
Loading

0 comments on commit 3090f94

Please sign in to comment.