본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

Prometheus 클라이언트 라이브러리 대 OpenTelemetry (Prometheus client libraries vs. OpenTelemetry)

원문 보기 위키 갱신

이 가이드는 Prometheus 클라이언트 라이브러리에 익숙한 개발자가 OpenTelemetry 메트릭 API와 SDK의 동등한 패턴을 이해할 수 있도록 돕습니다.

출처: 문서

본문

참고: 이 페이지는 Java와 Go를 다룹니다. 다른 언어의 예시는 계획되어 있습니다.

이 가이드는 Prometheus 클라이언트 라이브러리에 익숙한 개발자가 OpenTelemetry 메트릭 API와 SDK의 동등한 패턴을 이해할 수 있도록 돕습니다. 가장 일반적인 패턴을 다루지만, 완전한 목록은 아닙니다.

개념적 차이 (Conceptual differences)

코드를 살펴보기 전에 두 시스템 사이의 몇 가지 구조적 차이를 이해하는 것이 도움이 됩니다. Prometheus와 OpenMetrics 호환성 스펙은 두 시스템 사이의 완전한 변환 규칙을 문서화합니다. 이 섹션은 새 계측 코드를 작성할 때 가장 관련 있는 차이를 다룹니다.

레지스트리 (MeterProvider)

Prometheus에서 메트릭은 레지스트리에 등록됩니다. 기본적으로 전역 레지스트리입니다. 코드 어디서나 메트릭을 선언할 수 있으며, 등록되면 스크래핑에 사용할 수 있게 됩니다. 익스포터(HTTP 서버 또는 OTLP 푸시)는 별도의 독립적인 단계로 레지스트리에 부착됩니다.

OpenTelemetry에서 MeterProvider와 Meter는 메트릭 API의 일부입니다. MeterProvider에서 라이브러리 또는 컴포넌트 범위로 지정된 Meter를 얻고, 그 Meter에서 인스트루먼트를 생성합니다. 그 측정값이 어떻게 처리되는지(어떤 익스포터가 받는지, 어떻게 집계되는지, 어떤 일정으로)는 MeterProvider에 바인딩된 SDK와 그 구성에 의해 결정되며, 이는 계측 코드 자체와 분리되어 있습니다(API와 SDK 참조).

Prometheus처럼 OpenTelemetry는 전역 MeterProvider(계측 코드에서 명시적 배선이 필요 없음)와, 이를 지원하는 라이브러리에 전달할 수 있는 명시적 MeterProvider 인스턴스 모두를 지원합니다.

라벨 이름 (속성)

Prometheus는 메트릭 생성 시 라벨 이름을 선언해야 합니다. 라벨 값은 labelValues(...)를 통해 기록 시점에 바인딩됩니다.

OpenTelemetry에는 사전 라벨 선언이 없습니다. 속성 키와 값 모두 Attributes를 통해 측정 시점에 함께 제공됩니다.

네이밍 컨벤션

Prometheus는 snake_case 메트릭 이름을 사용합니다. 카운터 이름은 _total로 끝납니다. 관례상 Prometheus 메트릭 이름은 충돌을 피하기 위해 애플리케이션 또는 라이브러리 이름으로 접두사가 붙습니다(예: smart_home_hvac_on_seconds_total). 모든 메트릭이 평평한 전역 네임스페이스를 공유하기 때문입니다.

OpenTelemetry는 관례상 점(dotted) 이름을 사용합니다. 소유권과 네임스페이싱은 계측 범위(예: smart.home인 Meter 이름)에 담겨 있어, 메트릭 이름 자체에는 접두사가 필요 없습니다(예: hvac.on). Prometheus로 내보낼 때 익스포터는 이름을 변환합니다. 점은 밑줄이 되고, 단위 약어는 전체 단어로 확장되며(예: s → seconds), 카운터에는 _total 접미사가 붙습니다. 단위가 s인 OpenTelemetry 카운터 hvac.on은 hvac_on_seconds_total로 내보내집니다. 완전한 이름 변환 규칙 집합은 호환성 스펙을 참조하세요. 변환 전략은 구성 가능합니다. 예를 들어 UTF-8 문자를 보존하거나 단위·유형 접미사를 억제할 수 있습니다. 자세한 내용은 Prometheus 익스포터 구성 참조를 참조하세요.

상태 저장 및 콜백 인스트루먼트

두 시스템 모두 두 가지 기록 모드를 지원합니다.

  • Prometheus는 자체 누적 값을 유지하는 상태 저장 인스트루먼트(Counter, Gauge)를 스크래핑 시 현재 값을 반환하기 위해 콜백을 호출하는 함수 기반 인스트루먼트와 구분합니다. 네이밍은 클라이언트 라이브러리에 따라 다릅니다(Go의 GaugeFunc/CounterFunc, Java의 GaugeWithCallback/CounterWithCallback).
  • OpenTelemetry는 이것들을 동기(synchronous, counter, histogram 등)와 비동기(asynchronous, 등록된 콜백을 통해 관찰됨)라고 부릅니다. 시맨틱은 동일합니다.

또한 Prometheus Gauge는 두 개의 뚜렷한 OTel 인스트루먼트 유형을 포괄합니다. 비가산 값(온도 같은)을 위한 Gauge와, 증가하거나 감소할 수 있는 가산 값(활성 연결 같은)을 위한 UpDownCounter입니다. 자세한 내용은 Gauge를 참조하세요.

OTel: API와 SDK

OpenTelemetry는 계측을 구성과 분리하는 2계층 설계를 사용합니다. API 패키지와 SDK 패키지입니다. API는 메트릭을 기록하는 데 사용되는 인터페이스를 정의합니다. SDK는 구체적인 프로바이더, 익스포터, 처리 파이프라인인 구현을 제공합니다.

계측 코드는 API에만 의존해야 합니다. SDK는 애플리케이션 시작 시 한 번 구성되고 코드베이스의 나머지에 전달되는 API 참조에 배선됩니다. 이는 계측 라이브러리 코드를 특정 SDK 버전에서 분리하고, 테스트를 위해 no-op 구현을 쉽게 교체할 수 있게 합니다.

OTel: 계측 범위

Prometheus 메트릭은 전역적입니다. 프로세스의 모든 메트릭이 이름과 라벨로만 식별되는 같은 평평한 네임스페이스를 공유합니다.

OpenTelemetry는 각 인스트루먼트 그룹을 이름과 선택적 버전(예: smart.home)으로 식별되는 Meter로 범위를 지정합니다. Prometheus로 내보낼 때 범위 이름과 버전은 모든 메트릭 포인트에 otel_scope_name과 otel_scope_version 라벨로 추가됩니다. 추가 범위 속성도 otel_scope_[속성 이름]이라는 라벨로 추가됩니다. 이러한 라벨은 자동으로 나타나며 Prometheus에서 온 사용자에게 생소할 수 있습니다. 익스포터의 without_scope_info 옵션으로 억제할 수 있습니다. 자세한 내용은 Prometheus 익스포터 구성 참조를 참조하세요. 범위 정보 억제는 각 메트릭 이름이 단일 범위에 의해 생성될 때만 안전합니다. 두 범위가 같은 이름의 메트릭을 내보내면 범위 라벨이 그것들을 구분하는 유일한 수단입니다. 그 라벨이 없으면 출처를 구분할 방법 없는 중복 시계열이 되어 Prometheus에서 잘못된 출력을 생성합니다.

OTel: 집계 시간성

Prometheus 메트릭은 항상 누적(cumulative)입니다. OpenTelemetry는 누적과 델타 시간성 모두를 지원하지만, Prometheus 익스포터는 모든 인스트루먼트에 대해 누적을 강제합니다. Prometheus에서 마이그레이션하는 개발자에게 이는 투명합니다. 이미 의존하던 동작이 보존되기 때문입니다.

OTel: 리소스 속성

Prometheus는 스크래핑 대상에 job과 instance 라벨을 사용해 식별하며, 이 라벨은 스크래핑 시 Prometheus 서버에 의해 추가됩니다.

OpenTelemetry에는 프로세스의 모든 텔레메트리에 부착되는 구조화된 메타데이터인 Resource가 있으며, service.name과 service.instance.id 같은 속성을 가집니다. Prometheus로 내보낼 때 익스포터는 리소스 속성을 job과 instance 라벨로 매핑하고, 남은 속성은 target_info 메트릭으로 노출합니다(target_info는 OpenMetrics 1.0 관례입니다. 현재 Prometheus에서 수동으로 내보낸다면 OTel 동등물은 리소스 속성을 설정하는 것입니다). 정확한 매핑 규칙은 호환성 스펙을 참조하세요. target_info 메트릭은 without_target_info로 억제할 수 있고, 특정 리소스 속성은 with_resource_constant_labels로 메트릭 수준 라벨로 승격할 수 있습니다. 자세한 내용은 Prometheus 익스포터 구성 참조를 참조하세요.

초기화 (Initialization)

아래 예시는 두 가지 주요 배포 패턴을 다룹니다. Prometheus 스크래핑 엔드포인트 노출과 OTLP 엔드포인트로 푸시입니다.

Prometheus 스크래핑 엔드포인트 노출

Prometheus (Java)

package otel;

import io.prometheus.metrics.core.metrics.Counter;
import io.prometheus.metrics.exporter.httpserver.HTTPServer;
import java.io.IOException;

public class PrometheusScrapeInit {
  public static void main(String[] args) throws IOException, InterruptedException {
    // Create a counter and register it with the default PrometheusRegistry.
    Counter doorOpens =
        Counter.builder()
            .name("door_opens_total")
            .help("Total number of times a door has been opened")
            .labelNames("door")
            .register();

    // Start the HTTP server; Prometheus scrapes http://localhost:9464/metrics.
    HTTPServer server = HTTPServer.builder().port(9464).buildAndStart();
    Runtime.getRuntime().addShutdownHook(new Thread(server::close));

    doorOpens.labelValues("front").inc();

    Thread.currentThread().join(); // sleep forever
  }
}

OpenTelemetry (Java)

package otel;

import io.opentelemetry.api.OpenTelemetry;
import io.opentelemetry.api.common.AttributeKey;
import io.opentelemetry.api.common.Attributes;
import io.opentelemetry.api.metrics.LongCounter;
import io.opentelemetry.api.metrics.Meter;
import io.opentelemetry.exporter.prometheus.PrometheusHttpServer;
import io.opentelemetry.sdk.OpenTelemetrySdk;
import io.opentelemetry.sdk.metrics.SdkMeterProvider;

public class OtelScrapeInit {
  // Preallocate attribute keys and, when values are static, entire Attributes objects.
  private static final AttributeKey<String> DOOR = AttributeKey.stringKey("door");
  private static final Attributes FRONT_DOOR = Attributes.of(DOOR, "front");

  public static void main(String[] args) throws InterruptedException {
    // Configure the SDK: register a Prometheus reader that serves /metrics.
    OpenTelemetrySdk sdk =
        OpenTelemetrySdk.builder()
            .setMeterProvider(
                SdkMeterProvider.builder()
                    .registerMetricReader(PrometheusHttpServer.builder().setPort(9464).build())
                    .build())
            .build();
    Runtime.getRuntime().addShutdownHook(new Thread(sdk::close));

    // Instrumentation code uses the OpenTelemetry API type, not the SDK type directly.
    OpenTelemetry openTelemetry = sdk;

    // Metrics are served at http://localhost:9464/metrics.
    Meter meter = openTelemetry.getMeter("smart.home");
    LongCounter doorOpens =
        meter
            .counterBuilder("door.opens")
            .setDescription("Total number of times a door has been opened")
            .build();

    doorOpens.add(1, FRONT_DOOR);

    Thread.currentThread().join(); // sleep forever
  }
}

Prometheus (Go)

package main

import (
	"net/http"

	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/promhttp"
)

func main() {
	// Create a counter and register it with a custom registry.
	reg := prometheus.NewRegistry()
	doorOpens := prometheus.NewCounterVec(prometheus.CounterOpts{
		Name: "door_opens_total",
		Help: "Total number of times a door has been opened",
	}, []string{"door"})
	reg.MustRegister(doorOpens)

	// Prometheus scrapes http://localhost:9464/metrics.
	http.Handle("/metrics", promhttp.HandlerFor(reg, promhttp.HandlerOpts{}))
	go http.ListenAndServe(":9464", nil) //nolint:errcheck

	doorOpens.WithLabelValues("front").Inc()

	select {} // sleep forever
}

OpenTelemetry (Go)

package main

import (
	"context"
	"net/http"

	"github.com/prometheus/client_golang/prometheus/promhttp"
	"go.opentelemetry.io/otel/attribute"
	"go.opentelemetry.io/otel/exporters/prometheus"
	"go.opentelemetry.io/otel/metric"
	sdkmetric "go.opentelemetry.io/otel/sdk/metric"
)

func main() {
	ctx := context.Background()
	// Configure the SDK: register a Prometheus reader that serves /metrics.
	exporter, err := prometheus.New()
	if err != nil {
		panic(err)
	}
	provider := sdkmetric.NewMeterProvider(sdkmetric.WithReader(exporter))
	defer provider.Shutdown(ctx) //nolint:errcheck

	// Metrics are served at http://localhost:9464/metrics.
	http.Handle("/metrics", promhttp.Handler())
	go http.ListenAndServe(":9464", nil) //nolint:errcheck

	// Instrumentation code uses the API, not the SDK, directly.
	meter := provider.Meter("smart.home")
	doorOpens, err := meter.Int64Counter("door.opens",
		metric.WithDescription("Total number of times a door has been opened"))
	if err != nil {
		panic(err)
	}

	doorOpens.Add(ctx, 1, metric.WithAttributes(attribute.String("door", "front")))

	select {} // sleep forever
}

OTLP 엔드포인트로 메트릭 푸시

Prometheus (Java)

package otel;

import io.prometheus.metrics.core.metrics.Counter;
import io.prometheus.metrics.exporter.opentelemetry.OpenTelemetryExporter;

public class PrometheusOtlpInit {
  public static void main(String[] args) throws Exception {
    // Create a counter and register it with the default PrometheusRegistry.
    Counter doorOpens =
        Counter.builder()
            .name("door_opens_total")
            .help("Total number of times a door has been opened")
            .labelNames("door")
            .register();

    // Start the OTLP exporter. It reads from the default PrometheusRegistry and
    // pushes metrics to the configured endpoint on a fixed interval.
    OpenTelemetryExporter exporter =
        OpenTelemetryExporter.builder()
            .protocol("http/protobuf")
            .endpoint("http://localhost:4318")
            .intervalSeconds(60)
            .buildAndStart();
    Runtime.getRuntime().addShutdownHook(new Thread(exporter::close));

    doorOpens.labelValues("front").inc();

    Thread.currentThread().join(); // sleep forever
  }
}

OpenTelemetry (Java)

package otel;

import io.opentelemetry.api.OpenTelemetry;
import io.opentelemetry.api.metrics.LongCounter;
import io.opentelemetry.api.metrics.Meter;
import io.opentelemetry.exporter.otlp.http.metrics.OtlpHttpMetricExporter;
import io.opentelemetry.sdk.OpenTelemetrySdk;
import io.opentelemetry.sdk.metrics.SdkMeterProvider;
import io.opentelemetry.sdk.metrics.export.PeriodicMetricReader;
import java.time.Duration;

public class OtelOtlpInit {
  public static void main(String[] args) throws InterruptedException {
    // Configure the SDK: export metrics over OTLP/HTTP on a fixed interval.
    OpenTelemetrySdk sdk =
        OpenTelemetrySdk.builder()
            .setMeterProvider(
                SdkMeterProvider.builder()
                    .registerMetricReader(
                        PeriodicMetricReader.builder(
                                OtlpHttpMetricExporter.builder()
                                    .setEndpoint("http://localhost:4318")
                                    .build())
                            .setInterval(Duration.ofSeconds(60))
                            .build())
                    .build())
            .build();
    Runtime.getRuntime().addShutdownHook(new Thread(sdk::close));

    // Instrumentation code uses the OpenTelemetry API type, not the SDK type directly.
    OpenTelemetry openTelemetry = sdk;

    Meter meter = openTelemetry.getMeter("smart.home");
    LongCounter doorOpens =
        meter
            .counterBuilder("door.opens")
            .setDescription("Total number of times a door has been opened")
            .build();

    doorOpens.add(1);

    Thread.currentThread().join(); // sleep forever
  }
}

Prometheus (Go)

Prometheus Go 클라이언트 라이브러리에는 OTLP 푸시 익스포터가 포함되어 있지 않습니다.

OpenTelemetry (Go)

package main

import (
	"context"

	"go.opentelemetry.io/otel/attribute"
	"go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp"
	"go.opentelemetry.io/otel/metric"
	sdkmetric "go.opentelemetry.io/otel/sdk/metric"
)

func main() {
	ctx := context.Background()
	// Configure the SDK: export metrics over OTLP/HTTP on a fixed interval.
	// The endpoint defaults to localhost:4318 and can be configured via
	// the OTEL_EXPORTER_OTLP_ENDPOINT environment variable.
	exporter, err := otlpmetrichttp.New(ctx)
	if err != nil {
		panic(err)
	}
	provider := sdkmetric.NewMeterProvider(
		sdkmetric.WithReader(sdkmetric.NewPeriodicReader(exporter)),
	)
	defer provider.Shutdown(ctx) //nolint:errcheck

	meter := provider.Meter("smart.home")
	doorOpens, err := meter.Int64Counter("door.opens",
		metric.WithDescription("Total number of times a door has been opened"))
	if err != nil {
		panic(err)
	}

	doorOpens.Add(ctx, 1, metric.WithAttributes(attribute.String("door", "front")))

	select {} // sleep forever
}

카운터 (Counter)

카운터는 단조 증가하는 값을 기록합니다. Prometheus Counter는 OpenTelemetry Counter 인스트루먼트에 매핑됩니다.

  • 단위 인코딩: Prometheus는 단위를 메트릭 이름에 인코딩합니다(hvac_on_seconds_total). OpenTelemetry는 이름(hvac.on)과 단위(s)를 분리하며, Prometheus 익스포터가 단위 접미사를 자동으로 추가합니다.

카운터 (Counter)

Prometheus Counter에는 OpenTelemetry에 동등물이 없는 두 가지 시리즈 관리 기능이 포함되어 있습니다.

  • 시리즈 사전 초기화: Prometheus 클라이언트는 라벨 값 조합을 사전 초기화하여, 기록이 발생하기 전에 값 0으로 스크래핑 출력에 나타나게 할 수 있습니다. OpenTelemetry에는 동등물이 없습니다. 데이터 포인트는 첫 번째 add() 호출에 나타납니다.
  • 미리 바인딩된 시리즈: Prometheus 클라이언트는 labelValues()의 결과를 캐시하여 특정 라벨 값 조합에 미리 바인딩할 수 있습니다. 후속 호출은 내부 시리즈 조회를 건너뛰고 직접 데이터 포인트로 갑니다. OpenTelemetry에는 동등물이 없으며, 논의 중입니다.

Prometheus (Java)

package otel;

import io.prometheus.metrics.core.metrics.Counter;

public class PrometheusCounter {
  public static void counterUsage() {
    Counter hvacOnTime =
        Counter.builder()
            .name("hvac_on_seconds_total")
            .help("Total time the HVAC system has been running, in seconds")
            .labelNames("zone")
            .register();

    // Pre-bind to label value sets: subsequent calls go directly to the data point,
    // skipping the internal series lookup.
    var upstairs = hvacOnTime.labelValues("upstairs");
    var downstairs = hvacOnTime.labelValues("downstairs");

    upstairs.inc(127.5);
    downstairs.inc(3600.0);

    // Pre-initialize zones so they appear in /metrics with value 0 on startup.
    hvacOnTime.initLabelValues("basement");
  }
}

OpenTelemetry (Java)

package otel;

import io.opentelemetry.api.OpenTelemetry;
import io.opentelemetry.api.common.AttributeKey;
import io.opentelemetry.api.common.Attributes;
import io.opentelemetry.api.metrics.DoubleCounter;
import io.opentelemetry.api.metrics.Meter;

public class OtelCounter {
  // Preallocate attribute keys and, when values are static, entire Attributes objects.
  private static final AttributeKey<String> ZONE = AttributeKey.stringKey("zone");
  private static final Attributes UPSTAIRS = Attributes.of(ZONE, "upstairs");
  private static final Attributes DOWNSTAIRS = Attributes.of(ZONE, "downstairs");

  public static void counterUsage(OpenTelemetry openTelemetry) {
    Meter meter = openTelemetry.getMeter("smart.home");
    // HVAC on-time is fractional — use ofDoubles() to get a DoubleCounter.
    // No upfront label declaration: attributes are provided at record time.
    DoubleCounter hvacOnTime =
        meter
            .counterBuilder("hvac.on")
            .setDescription("Total time the HVAC system has been running")
            .setUnit("s")
            .ofDoubles()
            .build();

    hvacOnTime.add(127.5, UPSTAIRS);
    hvacOnTime.add(3600.0, DOWNSTAIRS);
  }
}

주요 차이점:

  • inc(value) → add(value). Prometheus와 달리 OpenTelemetry는 명시적인 값을 요구합니다. 단순 inc() 약칭이 없습니다.
  • OpenTelemetry는 LongCounter(정수, 기본값)를 DoubleCounter(.ofDoubles()로, 분수 값용)와 구분합니다. Prometheus는 단일 Counter 유형을 사용합니다.
  • 핫 경로에서 호출별 할당을 피하려면 AttributeKey 인스턴스(항상)와 Attributes 객체(값이 정적일 때)를 사전 할당하세요.

Prometheus (Go)

package main

import "github.com/prometheus/client_golang/prometheus"

var hvacOnTime = prometheus.NewCounterVec(prometheus.CounterOpts{
	Name: "hvac_on_seconds_total",
	Help: "Total time the HVAC system has been running, in seconds",
}, []string{"zone"})

func prometheusCounterUsage(reg *prometheus.Registry) {
	reg.MustRegister(hvacOnTime)

	// Pre-bind to label value sets: subsequent calls avoid the series lookup.
	upstairs := hvacOnTime.WithLabelValues("upstairs")
	downstairs := hvacOnTime.WithLabelValues("downstairs")

	upstairs.Add(127.5)
	downstairs.Add(3600.0)

	// Pre-initialize a series so it appears in /metrics with value 0.
	hvacOnTime.WithLabelValues("basement")
}

OpenTelemetry (Go)

package main

import (
	"context"

	"go.opentelemetry.io/otel/attribute"
	"go.opentelemetry.io/otel/metric"
)

// Preallocate attribute options when values are static to avoid per-call allocation.
var (
	zoneUpstairsOpts   = []metric.AddOption{metric.WithAttributes(attribute.String("zone", "upstairs"))}
	zoneDownstairsOpts = []metric.AddOption{metric.WithAttributes(attribute.String("zone", "downstairs"))}
)

func otelCounterUsage(ctx context.Context, meter metric.Meter) {
	// No upfront label declaration: attributes are provided at record time.
	hvacOnTime, err := meter.Float64Counter("hvac.on",
		metric.WithDescription("Total time the HVAC system has been running"),
		metric.WithUnit("s"))
	if err != nil {
		panic(err)
	}

	hvacOnTime.Add(ctx, 127.5, zoneUpstairsOpts...)
	hvacOnTime.Add(ctx, 3600.0, zoneDownstairsOpts...)
}

주요 차이점:

  • Add(value) → Add(ctx, value, metric.WithAttributes(...)). 모든 인스트루먼트 호출은 첫 번째 인자로 context.Context가 필요합니다.
  • Go에서 meter.Float64Counter와 meter.Int64Counter는 별개의 메서드입니다. Prometheus는 단일 Counter 유형을 사용합니다.
  • 인스트루먼트 생성은 (Instrument, error)를 반환하며 오류를 처리해야 합니다.

콜백(비동기) 카운터

총계가 외부 소스(장치 또는 런타임 같은)에 의해 유지되고, 직접 증가시키기보다 수집 시점에 관찰하려면 콜백 카운터(OpenTelemetry의 비동기 카운터)를 사용하세요.

Prometheus (Java)

package otel;

import io.prometheus.metrics.core.metrics.CounterWithCallback;

public class PrometheusCounterCallback {
  public static void counterCallbackUsage() {
    // Each zone has its own smart energy meter tracking cumulative joule totals.
    // Use a callback counter to report those values at scrape time without
    // maintaining separate counters in application code.
    CounterWithCallback.builder()
        .name("energy_consumed_joules_total")
        .help("Total energy consumed in joules")
        .labelNames("zone")
        .callback(
            callback -> {
              callback.call(SmartHomeDevices.totalEnergyJoules("upstairs"), "upstairs");
              callback.call(SmartHomeDevices.totalEnergyJoules("downstairs"), "downstairs");
            })
        .register();
  }
}

OpenTelemetry (Java)

package otel;

import io.opentelemetry.api.OpenTelemetry;
import io.opentelemetry.api.common.AttributeKey;
import io.opentelemetry.api.common.Attributes;
import io.opentelemetry.api.metrics.Meter;

public class OtelCounterCallback {
  private static final AttributeKey<String> ZONE = AttributeKey.stringKey("zone");
  private static final Attributes UPSTAIRS = Attributes.of(ZONE, "upstairs");
  private static final Attributes DOWNSTAIRS = Attributes.of(ZONE, "downstairs");

  public static void counterCallbackUsage(OpenTelemetry openTelemetry) {
    Meter meter = openTelemetry.getMeter("smart.home");
    // Each zone has its own smart energy meter tracking cumulative joule totals.
    // Use an asynchronous counter to report those values when a MetricReader
    // collects metrics, without maintaining separate counters in application code.
    meter
        .counterBuilder("energy.consumed")
        .setDescription("Total energy consumed")
        .setUnit("J")
        .ofDoubles()
        .buildWithCallback(
            measurement -> {
              measurement.record(SmartHomeDevices.totalEnergyJoules("upstairs"), UPSTAIRS);
              measurement.record(SmartHomeDevices.totalEnergyJoules("downstairs"), DOWNSTAIRS);
            });
  }
}

주요 차이점:

  • OpenTelemetry는 정수와 부동소수점 카운터를 구분합니다. .ofDoubles()는 부동소수점 변형을 선택합니다. Prometheus CounterWithCallback은 항상 부동소수점 값을 사용합니다.

Prometheus (Go)

package main

import "github.com/prometheus/client_golang/prometheus"

type energyCollector struct{ desc *prometheus.Desc }

func newEnergyCollector() *energyCollector {
	return &energyCollector{desc: prometheus.NewDesc(
		"energy_consumed_joules_total",
		"Total energy consumed in joules",
		[]string{"zone"}, nil,
	)}
}

func (c *energyCollector) Describe(ch chan<- *prometheus.Desc) { ch <- c.desc }
func (c *energyCollector) Collect(ch chan<- prometheus.Metric) {
	ch <- prometheus.MustNewConstMetric(c.desc, prometheus.CounterValue, totalEnergyJoules("upstairs"), "upstairs")
	ch <- prometheus.MustNewConstMetric(c.desc, prometheus.CounterValue, totalEnergyJoules("downstairs"), "downstairs")
}

func prometheusCounterCallbackUsage(reg *prometheus.Registry) {
	// Each zone has its own smart energy meter tracking cumulative joule totals.
	// Implement prometheus.Collector to report those values at scrape time.
	reg.MustRegister(newEnergyCollector())
}

OpenTelemetry (Go)

package main

import (
	"context"

	"go.opentelemetry.io/otel/attribute"
	"go.opentelemetry.io/otel/metric"
)

var (
	zoneUpstairs   = attribute.String("zone", "upstairs")
	zoneDownstairs = attribute.String("zone", "downstairs")
)

func otelCounterCallbackUsage(meter metric.Meter) {
	// Each zone has its own smart energy meter tracking cumulative joule totals.
	// Use an observable counter to report those values when metrics are collected.
	_, err := meter.Float64ObservableCounter("energy.consumed",
		metric.WithDescription("Total energy consumed"),
		metric.WithUnit("J"),
		metric.WithFloat64Callback(func(_ context.Context, o metric.Float64Observer) error {
			o.Observe(totalEnergyJoules("upstairs"), metric.WithAttributes(zoneUpstairs))
			o.Observe(totalEnergyJoules("downstairs"), metric.WithAttributes(zoneDownstairs))
			return nil
		}))
	if err != nil {
		panic(err)
	}
}

주요 차이점:

  • Prometheus 예시는 라벨이 있는 카운터 값을 보고하기 위해 Describe와 Collect 메서드로 prometheus.Collector를 구현합니다.
  • OpenTelemetry는 Float64ObservableCounter를 Int64ObservableCounter와 구분합니다.

게이지 (Gauge)

게이지는 증가하거나 감소할 수 있는 순간 값을 기록합니다. Prometheus는 그러한 모든 값에 단일 Gauge 유형을 사용하지만, OpenTelemetry는 올바른 인스트루먼트를 선택할 때 가산(additive) 값과 비가산(non-additive) 값을 구분합니다.

  • 비가산 값은 인스턴스 간에 의미 있게 합산될 수 없습니다. 예를 들어 온도는 세 개의 방 센서의 판독값을 더해도 유용한 숫자가 나오지 않습니다. 이들은 OTel Gauge와 ObservableGauge에 매핑됩니다.
  • 가산 값은 인스턴스 간에 의미 있게 합산될 수 있습니다. 예를 들어 서비스 인스턴스 간에 합산된 연결된 장치 개수는 유용한 총계를 줍니다. 이들은 OTel UpDownCounter와 ObservableUpDownCounter에 매핑됩니다.

이 구분은 모든 게이지 패턴(abs, inc와 dec, 콜백 변형)에 적용됩니다. 더 자세한 설명은 인스트루먼트 선택 가이드를 참조하세요.

게이지 — abs

구성 값이나 장치 설정점 같은 절대값으로 기록되는 값에는 이 패턴을 사용하세요. Prometheus Gauge는 OpenTelemetry Gauge 인스트루먼트에 매핑됩니다.

Prometheus (Java)

package otel;

import io.prometheus.metrics.core.metrics.Gauge;

public class PrometheusGauge {
  public static void gaugeUsage() {
    Gauge thermostatSetpoint =
        Gauge.builder()
            .name("thermostat_setpoint_celsius")
            .help("Target temperature set on the thermostat")
            .labelNames("zone")
            .register();

    thermostatSetpoint.labelValues("upstairs").set(22.5);
    thermostatSetpoint.labelValues("downstairs").set(20.0);
  }
}

OpenTelemetry (Java)

package otel;

import io.opentelemetry.api.OpenTelemetry;
import io.opentelemetry.api.common.AttributeKey;
import io.opentelemetry.api.common.Attributes;
import io.opentelemetry.api.metrics.DoubleGauge;
import io.opentelemetry.api.metrics.Meter;

public class OtelGauge {
  // Preallocate attribute keys and, when values are static, entire Attributes objects.
  private static final AttributeKey<String> ZONE = AttributeKey.stringKey("zone");
  private static final Attributes UPSTAIRS = Attributes.of(ZONE, "upstairs");
  private static final Attributes DOWNSTAIRS = Attributes.of(ZONE, "downstairs");

  public static void gaugeUsage(OpenTelemetry openTelemetry) {
    Meter meter = openTelemetry.getMeter("smart.home");
    DoubleGauge thermostatSetpoint =
        meter
            .gaugeBuilder("thermostat.setpoint")
            .setDescription("Target temperature set on the thermostat")
            .setUnit("Cel")
            .build();

    thermostatSetpoint.set(22.5, UPSTAIRS);
    thermostatSetpoint.set(20.0, DOWNSTAIRS);
  }
}

주요 차이점:

  • set(value) → set(value, attributes). 메서드 이름은 같습니다.
  • OpenTelemetry는 LongGauge(정수, .ofLongs()로)를 DoubleGauge(기본값)와 구분합니다. Prometheus는 단일 Gauge 유형을 사용합니다.
  • 핫 경로에서 호출별 할당을 피하려면 AttributeKey 인스턴스(항상)와 Attributes 객체(값이 정적일 때)를 사전 할당하세요.

Prometheus (Go)

package main

import "github.com/prometheus/client_golang/prometheus"

var thermostatSetpoint = prometheus.NewGaugeVec(prometheus.GaugeOpts{
	Name: "thermostat_setpoint_celsius",
	Help: "Target temperature set on the thermostat",
}, []string{"zone"})

func prometheusGaugeUsage(reg *prometheus.Registry) {
	reg.MustRegister(thermostatSetpoint)

	thermostatSetpoint.WithLabelValues("upstairs").Set(22.5)
	thermostatSetpoint.WithLabelValues("downstairs").Set(20.0)
}

OpenTelemetry (Go)

package main

import (
	"context"

	"go.opentelemetry.io/otel/attribute"
	"go.opentelemetry.io/otel/metric"
)

// Preallocate attribute options when values are static to avoid per-call allocation.
var (
	zoneUpstairsGaugeOpts   = []metric.RecordOption{metric.WithAttributes(attribute.String("zone", "upstairs"))}
	zoneDownstairsGaugeOpts = []metric.RecordOption{metric.WithAttributes(attribute.String("zone", "downstairs"))}
)

func otelGaugeUsage(ctx context.Context, meter metric.Meter) {
	thermostatSetpoint, err := meter.Float64Gauge("thermostat.setpoint",
		metric.WithDescription("Target temperature set on the thermostat"),
		metric.WithUnit("Cel"))
	if err != nil {
		panic(err)
	}

	thermostatSetpoint.Record(ctx, 22.5, zoneUpstairsGaugeOpts...)
	thermostatSetpoint.Record(ctx, 20.0, zoneDownstairsGaugeOpts...)
}

주요 차이점:

  • Set(value) → Record(ctx, value, metric.WithAttributes(...)).
  • Go에서 meter.Float64Gauge와 meter.Int64Gauge는 별개의 메서드입니다. Prometheus는 단일 Gauge 유형을 사용합니다.

콜백 게이지 — abs

비가산 값이 센서 판독값 같이 외부에서 유지되고, 직접 추적하기보다 수집 시점에 관찰하려면 콜백 게이지(OpenTelemetry의 비동기 게이지)를 사용하세요.

Prometheus (Java)

package otel;

import io.prometheus.metrics.core.metrics.GaugeWithCallback;

public class PrometheusGaugeCallback {
  public static void gaugeCallbackUsage() {
    // Temperature sensors maintain their own readings in firmware.
    // Use a callback gauge to report those values at scrape time without
    // maintaining a separate gauge in application code.
    GaugeWithCallback.builder()
        .name("room_temperature_celsius")
        .help("Current temperature in the room")
        .labelNames("room")
        .callback(
            callback -> {
              callback.call(SmartHomeDevices.livingRoomTemperatureCelsius(), "living_room");
              callback.call(SmartHomeDevices.bedroomTemperatureCelsius(), "bedroom");
            })
        .register();
  }
}

OpenTelemetry (Java)

package otel;

import io.opentelemetry.api.OpenTelemetry;
import io.opentelemetry.api.common.AttributeKey;
import io.opentelemetry.api.common.Attributes;
import io.opentelemetry.api.metrics.Meter;

public class OtelGaugeCallback {
  private static final AttributeKey<String> ROOM = AttributeKey.stringKey("room");
  private static final Attributes LIVING_ROOM = Attributes.of(ROOM, "living_room");
  private static final Attributes BEDROOM = Attributes.of(ROOM, "bedroom");

  public static void gaugeCallbackUsage(OpenTelemetry openTelemetry) {
    Meter meter = openTelemetry.getMeter("smart.home");
    // Temperature sensors maintain their own readings in firmware.
    // Use an asynchronous gauge to report those values when a MetricReader
    // collects metrics, without maintaining separate gauges in application code.
    meter
        .gaugeBuilder("room.temperature")
        .setDescription("Current temperature in the room")
        .setUnit("Cel")
        .buildWithCallback(
            measurement -> {
              measurement.record(SmartHomeDevices.livingRoomTemperatureCelsius(), LIVING_ROOM);
              measurement.record(SmartHomeDevices.bedroomTemperatureCelsius(), BEDROOM);
            });
  }
}

Prometheus (Go)

package main

import "github.com/prometheus/client_golang/prometheus"

type temperatureCollector struct{ desc *prometheus.Desc }

func newTemperatureCollector() *temperatureCollector {
	return &temperatureCollector{desc: prometheus.NewDesc(
		"room_temperature_celsius",
		"Current temperature in the room",
		[]string{"room"}, nil,
	)}
}

func (c *temperatureCollector) Describe(ch chan<- *prometheus.Desc) { ch <- c.desc }
func (c *temperatureCollector) Collect(ch chan<- prometheus.Metric) {
	ch <- prometheus.MustNewConstMetric(c.desc, prometheus.GaugeValue, livingRoomTemperatureCelsius(), "living_room")
	ch <- prometheus.MustNewConstMetric(c.desc, prometheus.GaugeValue, bedroomTemperatureCelsius(), "bedroom")
}

func prometheusGaugeCallbackUsage(reg *prometheus.Registry) {
	// Temperature sensors maintain their own readings in firmware.
	// Implement prometheus.Collector to report those values at scrape time.
	reg.MustRegister(newTemperatureCollector())
}

OpenTelemetry (Go)

package main

import (
	"context"

	"go.opentelemetry.io/otel/attribute"
	"go.opentelemetry.io/otel/metric"
)

var (
	roomLivingRoom = attribute.String("room", "living_room")
	roomBedroom    = attribute.String("room", "bedroom")
)

func otelGaugeCallbackUsage(meter metric.Meter) {
	// Temperature sensors maintain their own readings in firmware.
	// Use an observable gauge to report those values when metrics are collected.
	_, err := meter.Float64ObservableGauge("room.temperature",
		metric.WithDescription("Current temperature in the room"),
		metric.WithUnit("Cel"),
		metric.WithFloat64Callback(func(_ context.Context, o metric.Float64Observer) error {
			o.Observe(livingRoomTemperatureCelsius(), metric.WithAttributes(roomLivingRoom))
			o.Observe(bedroomTemperatureCelsius(), metric.WithAttributes(roomBedroom))
			return nil
		}))
	if err != nil {
		panic(err)
	}
}

주요 차이점:

  • Prometheus 예시는 라벨이 있는 게이지 값을 보고하기 위해 Describe와 Collect 메서드로 prometheus.Collector를 구현합니다.

게이지 — inc와 dec

Prometheus Gauge는 점진적으로 변하는 값(연결된 장치 수나 활성 세션 같은)에 대한 증가와 감소를 지원합니다. OpenTelemetry Gauge는 절대값만 기록합니다. 이 패턴은 OpenTelemetry UpDownCounter 인스트루먼트에 매핑됩니다.

Prometheus (Java)

package otel;

import io.prometheus.metrics.core.metrics.Gauge;

public class PrometheusUpDownCounter {
  public static void upDownCounterUsage() {
    // Prometheus uses Gauge for values that can increase or decrease.
    Gauge devicesConnected =
        Gauge.builder()
            .name("devices_connected")
            .help("Number of smart home devices currently connected")
            .labelNames("device_type")
            .register();

    // Increment when a device connects, decrement when it disconnects.
    devicesConnected.labelValues("thermostat").inc();
    devicesConnected.labelValues("thermostat").inc();
    devicesConnected.labelValues("lock").inc();
    devicesConnected.labelValues("lock").dec();
  }
}

OpenTelemetry (Java)

package otel;

import io.opentelemetry.api.OpenTelemetry;
import io.opentelemetry.api.common.AttributeKey;
import io.opentelemetry.api.common.Attributes;
import io.opentelemetry.api.metrics.LongUpDownCounter;
import io.opentelemetry.api.metrics.Meter;

public class OtelUpDownCounter {
  // Preallocate attribute keys and, when values are static, entire Attributes objects.
  private static final AttributeKey<String> DEVICE_TYPE = AttributeKey.stringKey("device_type");
  private static final Attributes THERMOSTAT = Attributes.of(DEVICE_TYPE, "thermostat");
  private static final Attributes LOCK = Attributes.of(DEVICE_TYPE, "lock");

  public static void upDownCounterUsage(OpenTelemetry openTelemetry) {
    Meter meter = openTelemetry.getMeter("smart.home");
    LongUpDownCounter devicesConnected =
        meter
            .upDownCounterBuilder("devices.connected")
            .setDescription("Number of smart home devices currently connected")
            .build();

    // add() accepts positive and negative values.
    devicesConnected.add(1, THERMOSTAT);
    devicesConnected.add(1, THERMOSTAT);
    devicesConnected.add(1, LOCK);
    devicesConnected.add(-1, LOCK);
  }
}

주요 차이점:

  • inc() / dec() → add(1) / add(-1). add()는 양수와 음수 값을 모두 받아들입니다.
  • Prometheus 유형은 Gauge이고, OpenTelemetry 유형은 LongUpDownCounter(.ofDoubles()로 DoubleUpDownCounter)입니다.

Prometheus (Go)

package main

import "github.com/prometheus/client_golang/prometheus"

// Prometheus uses Gauge for values that can increase or decrease.
var devicesConnected = prometheus.NewGaugeVec(prometheus.GaugeOpts{
	Name: "devices_connected",
	Help: "Number of smart home devices currently connected",
}, []string{"device_type"})

func prometheusUpDownCounterUsage(reg *prometheus.Registry) {
	reg.MustRegister(devicesConnected)

	// Increment when a device connects, decrement when it disconnects.
	devicesConnected.WithLabelValues("thermostat").Inc()
	devicesConnected.WithLabelValues("thermostat").Inc()
	devicesConnected.WithLabelValues("lock").Inc()
	devicesConnected.WithLabelValues("lock").Dec()
}

OpenTelemetry (Go)

package main

import (
	"context"

	"go.opentelemetry.io/otel/attribute"
	"go.opentelemetry.io/otel/metric"
)

// Preallocate attribute options when values are static to avoid per-call allocation.
var (
	deviceThermostatAddOpts = []metric.AddOption{metric.WithAttributes(attribute.String("device_type", "thermostat"))}
	deviceLockAddOpts       = []metric.AddOption{metric.WithAttributes(attribute.String("device_type", "lock"))}
)

func otelUpDownCounterUsage(ctx context.Context, meter metric.Meter) {
	devicesConnected, err := meter.Int64UpDownCounter("devices.connected",
		metric.WithDescription("Number of smart home devices currently connected"))
	if err != nil {
		panic(err)
	}

	// Add() accepts positive and negative values.
	devicesConnected.Add(ctx, 1, deviceThermostatAddOpts...)
	devicesConnected.Add(ctx, 1, deviceThermostatAddOpts...)
	devicesConnected.Add(ctx, 1, deviceLockAddOpts...)
	devicesConnected.Add(ctx, -1, deviceLockAddOpts...)
}

주요 차이점:

  • Inc() / Dec() → Add(ctx, 1, ...) / Add(ctx, -1, ...). Add()는 양수와 음수 값을 모두 받아들입니다.
  • Prometheus 유형은 Gauge이고, OpenTelemetry 유형은 Int64UpDownCounter(meter.Float64UpDownCounter로 Float64UpDownCounter)입니다.

콜백 게이지 — inc와 dec

가산 개수가 그렇지 않으면 inc()/dec()로 추적될 텐데 장치 관리자나 연결 풀 같이 외부에서 유지되고, 수집 시점에 관찰하려면 콜백 게이지(OpenTelemetry의 비동기 업다운 카운터)를 사용하세요.

Prometheus (Java)

package otel;

import io.prometheus.metrics.core.metrics.GaugeWithCallback;

public class PrometheusUpDownCounterCallback {
  public static void upDownCounterCallbackUsage() {
    // The device manager maintains the count of connected devices.
    // Use a callback gauge to report that value at scrape time.
    GaugeWithCallback.builder()
        .name("devices_connected")
        .help("Number of smart home devices currently connected")
        .labelNames("device_type")
        .callback(
            callback -> {
              callback.call(SmartHomeDevices.connectedDeviceCount("thermostat"), "thermostat");
              callback.call(SmartHomeDevices.connectedDeviceCount("lock"), "lock");
            })
        .register();
  }
}

OpenTelemetry (Java)

package otel;

import io.opentelemetry.api.OpenTelemetry;
import io.opentelemetry.api.common.AttributeKey;
import io.opentelemetry.api.common.Attributes;
import io.opentelemetry.api.metrics.Meter;

public class OtelUpDownCounterCallback {
  private static final AttributeKey<String> DEVICE_TYPE = AttributeKey.stringKey("device_type");
  private static final Attributes THERMOSTAT = Attributes.of(DEVICE_TYPE, "thermostat");
  private static final Attributes LOCK = Attributes.of(DEVICE_TYPE, "lock");

  public static void upDownCounterCallbackUsage(OpenTelemetry openTelemetry) {
    Meter meter = openTelemetry.getMeter("smart.home");
    // The device manager maintains the count of connected devices.
    // Use an asynchronous up-down counter to report that value when a MetricReader
    // collects metrics.
    meter
        .upDownCounterBuilder("devices.connected")
        .setDescription("Number of smart home devices currently connected")
        .buildWithCallback(
            measurement -> {
              measurement.record(SmartHomeDevices.connectedDeviceCount("thermostat"), THERMOSTAT);
              measurement.record(SmartHomeDevices.connectedDeviceCount("lock"), LOCK);
            });
  }
}

Prometheus (Go)

package main

import "github.com/prometheus/client_golang/prometheus"

type deviceCountCollector struct{ desc *prometheus.Desc }

func newDeviceCountCollector() *deviceCountCollector {
	return &deviceCountCollector{desc: prometheus.NewDesc(
		"devices_connected",
		"Number of smart home devices currently connected",
		[]string{"device_type"}, nil,
	)}
}

func (c *deviceCountCollector) Describe(ch chan<- *prometheus.Desc) { ch <- c.desc }
func (c *deviceCountCollector) Collect(ch chan<- prometheus.Metric) {
	ch <- prometheus.MustNewConstMetric(c.desc, prometheus.GaugeValue, float64(connectedDeviceCount("thermostat")), "thermostat")
	ch <- prometheus.MustNewConstMetric(c.desc, prometheus.GaugeValue, float64(connectedDeviceCount("lock")), "lock")
}

func prometheusUpDownCounterCallbackUsage(reg *prometheus.Registry) {
	// The device manager maintains the count of connected devices.
	// Implement prometheus.Collector to report those values at scrape time.
	reg.MustRegister(newDeviceCountCollector())
}

OpenTelemetry (Go)

package main

import (
	"context"

	"go.opentelemetry.io/otel/attribute"
	"go.opentelemetry.io/otel/metric"
)

var (
	deviceThermostat = attribute.String("device_type", "thermostat")
	deviceLock       = attribute.String("device_type", "lock")
)

func otelUpDownCounterCallbackUsage(meter metric.Meter) {
	// The device manager maintains the count of connected devices.
	// Use an observable up-down counter to report that value when metrics are collected.
	_, err := meter.Int64ObservableUpDownCounter("devices.connected",
		metric.WithDescription("Number of smart home devices currently connected"),
		metric.WithInt64Callback(func(_ context.Context, o metric.Int64Observer) error {
			o.Observe(int64(connectedDeviceCount("thermostat")), metric.WithAttributes(deviceThermostat))
			o.Observe(int64(connectedDeviceCount("lock")), metric.WithAttributes(deviceLock))
			return nil
		}))
	if err != nil {
		panic(err)
	}
}

주요 차이점:

  • Prometheus 예시는 라벨이 있는 게이지 값을 보고하기 위해 Describe와 Collect 메서드로 prometheus.Collector를 구현합니다.
  • Int64ObservableUpDownCounter는 metric.WithInt64Callback을 사용합니다.

히스토그램 (Histogram)

히스토그램은 일련의 측정값 분포를 기록하며, 관측 횟수, 그 합, 구성 가능한 버킷 경계 내에 속하는 수를 추적합니다.

Prometheus와 OpenTelemetry 모두 클래식(명시적 버킷) 히스토그램과 네이티브(base2 지수) 히스토그램을 지원합니다. Prometheus에는 또한 Summary 유형이 있는데, 이는 직접적인 OTel 동등물이 없습니다. 아래 Summary를 참조하세요.

Prometheus Histogram은 OpenTelemetry Histogram 인스트루먼트에 매핑됩니다.

클래식(명시적) 히스토그램

두 시스템 모두 고정 버킷 경계가 관측을 이산 범위로 나누는 클래식 히스토그램을 지원합니다.

  • 버킷 구성: Prometheus는 생성 시 인스트루먼트 자체에 버킷 경계를 선언합니다. OpenTelemetry에서 버킷 경계는 SDK 수준에서 구성된 뷰에 의해 오버라이드되거나 대체될 수 있는 힌트로 인스트루먼트에 설정됩니다. 이 분리는 계측 코드를 수집 구성과 독립적으로 유지합니다. 경계가 지정되지 않고 뷰가 구성되지 않으면 SDK는 밀리초 규모의 대기 시간에 맞게 설계된 기본 세트([0, 5, 10, 25, 50, 75, 100, 250, 500, 750, 1000, 2500, 5000, 7500, 10000])를 사용하며, 이는 초 단위 측정에 대해서는 잘못된 것일 수 있습니다. 기존 히스토그램을 마이그레이션할 때는 항상 경계를 제공하거나 뷰를 구성하세요.

Prometheus (Java)

package otel;

import io.prometheus.metrics.core.metrics.Histogram;

public class PrometheusHistogram {
  public static void histogramUsage() {
    Histogram deviceCommandDuration =
        Histogram.builder()
            .name("device_command_duration_seconds")
            .help("Time to receive acknowledgment from a smart home device")
            .labelNames("device_type")
            .classicUpperBounds(0.1, 0.25, 0.5, 1.0, 2.5, 5.0)
            .register();

    deviceCommandDuration.labelValues("thermostat").observe(0.35);
    deviceCommandDuration.labelValues("lock").observe(0.85);
  }
}

OpenTelemetry (Java)

package otel;

import io.opentelemetry.api.OpenTelemetry;
import io.opentelemetry.api.common.AttributeKey;
import io.opentelemetry.api.common.Attributes;
import io.opentelemetry.api.metrics.DoubleHistogram;
import io.opentelemetry.api.metrics.Meter;
import java.util.List;

public class OtelHistogram {
  // Preallocate attribute keys and, when values are static, entire Attributes objects.
  private static final AttributeKey<String> DEVICE_TYPE = AttributeKey.stringKey("device_type");
  private static final Attributes THERMOSTAT = Attributes.of(DEVICE_TYPE, "thermostat");
  private static final Attributes LOCK = Attributes.of(DEVICE_TYPE, "lock");

  public static void histogramUsage(OpenTelemetry openTelemetry) {
    Meter meter = openTelemetry.getMeter("smart.home");
    // setExplicitBucketBoundariesAdvice() sets default boundaries as a hint to the SDK.
    // Views configured at the SDK level take precedence over this advice.
    DoubleHistogram deviceCommandDuration =
        meter
            .histogramBuilder("device.command.duration")
            .setDescription("Time to receive acknowledgment from a smart home device")
            .setUnit("s")
            .setExplicitBucketBoundariesAdvice(List.of(0.1, 0.25, 0.5, 1.0, 2.5, 5.0))
            .build();

    deviceCommandDuration.record(0.35, THERMOSTAT);
    deviceCommandDuration.record(0.85, LOCK);
  }
}

주요 차이점:

  • observe(value) → record(value, attributes).
  • OpenTelemetry는 LongHistogram(정수, .ofLongs()로)을 DoubleHistogram(기본값)과 구분합니다. Prometheus는 단일 Histogram 유형을 사용합니다.
  • 핫 경로에서 호출별 할당을 피하려면 AttributeKey 인스턴스(항상)와 Attributes 객체(값이 정적일 때)를 사전 할당하세요.
  • SDK 뷰는 setExplicitBucketBoundariesAdvice()로 설정된 경계를 오버라이드할 수 있고, 속성 필터링, min/max 기록, 인스트루먼트 이름 변경 같은 히스토그램 수집의 다른 측면도 구성할 수 있습니다.

Prometheus (Go)

package main

import "github.com/prometheus/client_golang/prometheus"

var deviceCommandDuration = prometheus.NewHistogramVec(prometheus.HistogramOpts{
	Name:    "device_command_duration_seconds",
	Help:    "Time to receive acknowledgment from a smart home device",
	Buckets: []float64{0.1, 0.25, 0.5, 1.0, 2.5, 5.0},
}, []string{"device_type"})

func prometheusHistogramUsage(reg *prometheus.Registry) {
	reg.MustRegister(deviceCommandDuration)

	deviceCommandDuration.WithLabelValues("thermostat").Observe(0.35)
	deviceCommandDuration.WithLabelValues("lock").Observe(0.85)
}

OpenTelemetry (Go)

package main

import (
	"context"

	"go.opentelemetry.io/otel/attribute"
	"go.opentelemetry.io/otel/metric"
)

// Preallocate attribute options when values are static to avoid per-call allocation.
var (
	deviceThermostatOpts = []metric.RecordOption{metric.WithAttributes(attribute.String("device_type", "thermostat"))}
	deviceLockOpts       = []metric.RecordOption{metric.WithAttributes(attribute.String("device_type", "lock"))}
)

func otelHistogramUsage(ctx context.Context, meter metric.Meter) {
	// WithExplicitBucketBoundaries sets default boundaries as a hint to the SDK.
	// Views configured at the SDK level take precedence over this hint.
	deviceCommandDuration, err := meter.Float64Histogram("device.command.duration",
		metric.WithDescription("Time to receive acknowledgment from a smart home device"),
		metric.WithUnit("s"),
		metric.WithExplicitBucketBoundaries(0.1, 0.25, 0.5, 1.0, 2.5, 5.0))
	if err != nil {
		panic(err)
	}

	deviceCommandDuration.Record(ctx, 0.35, deviceThermostatOpts...)
	deviceCommandDuration.Record(ctx, 0.85, deviceLockOpts...)
}

주요 차이점:

  • Observe(value) → Record(ctx, value, metric.WithAttributes(...)).
  • Go에서 metric.WithExplicitBucketBoundaries(...)는 가변 인자입니다(슬라이스가 아님). Prometheus는 HistogramOpts의 Buckets 필드를 사용합니다.
  • SDK 뷰는 WithExplicitBucketBoundaries()로 설정된 경계를 오버라이드할 수 있고, 속성 필터링, min/max 기록, 인스트루먼트 이름 변경 같은 히스토그램 수집의 다른 측면도 구성할 수 있습니다.

네이티브 (base2 지수) 히스토그램

두 시스템 모두 관찰된 범위를 수동 구성 없이 포괄하도록 버킷 경계를 자동으로 조정하는 네이티브(base2 지수) 히스토그램을 지원합니다.

  • 형식 선택: Prometheus 인스트루먼트는 클래식 형식만, 네이티브 형식만, 또는 둘 다 동시에 내보낼 수 있어, 계측 변경 없이 점진적 마이그레이션을 가능하게 합니다. OpenTelemetry에서 형식 선택은 계측 코드 외부(익스포터 또는 뷰를 통해)에서 구성되므로, 계측 코드는 어느 쪽이든 변경이 필요 없습니다.
  • 계측 코드: OpenTelemetry 계측 코드는 클래식과 네이티브 히스토그램에 대해 동일합니다. 같은 record() 호출이 SDK가 어떻게 구성되었는지에 따라 어느 형식이든 생성합니다.

Prometheus (Java)

Prometheus에서 히스토그램 형식은 인스트루먼트 생성 시 제어됩니다. 아래 예시는 네이티브 형식으로 제한하기 위해 .nativeOnly()를 사용합니다. 그것을 생략하면 클래식과 네이티브 형식을 동시에 내보냅니다.

package otel;

import io.prometheus.metrics.core.metrics.Histogram;

public class PrometheusHistogramNative {
  public static void nativeHistogramUsage() {
    Histogram deviceCommandDuration =
        Histogram.builder()
            .name("device_command_duration_seconds")
            .help("Time to receive acknowledgment from a smart home device")
            .labelNames("device_type")
            .nativeOnly()
            .register();

    deviceCommandDuration.labelValues("thermostat").observe(0.35);
    deviceCommandDuration.labelValues("lock").observe(0.85);
  }
}

Prometheus (Go)

Prometheus에서 NativeHistogramBucketFactor를 설정하면 클래식 버킷 구성과 함께 네이티브 히스토그램이 활성화됩니다. 두 형식 모두 동시에 보고됩니다.

package main

import "github.com/prometheus/client_golang/prometheus"

var nativeDeviceCommandDuration = prometheus.NewHistogramVec(prometheus.HistogramOpts{
	Name:                        "device_command_duration_seconds",
	Help:                        "Time to receive acknowledgment from a smart home device",
	NativeHistogramBucketFactor: 1.1,
}, []string{"device_type"})

func nativeHistogramUsage(reg *prometheus.Registry) {
	reg.MustRegister(nativeDeviceCommandDuration)

	nativeDeviceCommandDuration.WithLabelValues("thermostat").Observe(0.35)
	nativeDeviceCommandDuration.WithLabelValues("lock").Observe(0.85)
}

주요 차이점:

  • Go에서 네이티브 히스토그램을 활성화하려면 NativeHistogramBucketFactor를 1.0보다 큰 값으로 설정해야 합니다. 선택 사항이 아닙니다. 0(제로 값)으로 설정하면 네이티브 히스토그램이 완전히 비활성화됩니다. 이 값은 연속 버킷 경계 사이의 최대 비율을 제어합니다. 더 작은 값은 더 많은 버킷을 대가로 더 세밀한 해상도를 제공합니다. 일반적으로 사용되는 1.1 값과 같은 버킷 밀도를 근사하려면 AggregationBase2ExponentialHistogram에 MaxScale: 3을 설정하세요.

OpenTelemetry에서 계측 코드는 클래식 히스토그램의 경우와 동일합니다. base2 지수 형식은 계측 계층 외부에서 별도로 구성됩니다.

선호되는 접근 방식은 메트릭 익스포터에서 구성하는 것입니다. 이것은 계측 코드를 건드리지 않고 해당 익스포터를 통해 내보내지는 모든 히스토그램에 적용됩니다.

Java

package otel;

import io.opentelemetry.exporter.otlp.http.metrics.OtlpHttpMetricExporter;
import io.opentelemetry.sdk.metrics.Aggregation;
import io.opentelemetry.sdk.metrics.InstrumentType;
import io.opentelemetry.sdk.metrics.export.DefaultAggregationSelector;

public class OtelHistogramExponentialExporter {
  static OtlpHttpMetricExporter createExporter() {
    // Configure the exporter to use exponential histograms for all histogram instruments.
    // This is the preferred approach — it applies globally without modifying instrumentation code.
    return OtlpHttpMetricExporter.builder()
        .setEndpoint("http://localhost:4318")
        .setDefaultAggregationSelector(
            DefaultAggregationSelector.getDefault()
                .with(InstrumentType.HISTOGRAM, Aggregation.base2ExponentialBucketHistogram()))
        .build();
  }
}

Go

package main

import (
	"context"

	"go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp"
	sdkmetric "go.opentelemetry.io/otel/sdk/metric"
)

func createExponentialExporter(ctx context.Context) (*otlpmetrichttp.Exporter, error) {
	// Configure the exporter to use exponential histograms for all histogram instruments.
	// This is the preferred approach — it applies globally without modifying instrumentation code.
	return otlpmetrichttp.New(ctx,
		otlpmetrichttp.WithAggregationSelector(func(ik sdkmetric.InstrumentKind) sdkmetric.Aggregation {
			if ik == sdkmetric.InstrumentKindHistogram {
				return sdkmetric.AggregationBase2ExponentialHistogram{}
			}
			return sdkmetric.DefaultAggregationSelector(ik)
		}),
	)
}

더 세밀한 통제를 위해, 예를 들어 다른 인스트루먼트는 명시적 버킷을 유지하면서 특정 인스트루먼트에 base2 지수 히스토그램을 사용하려면 뷰를 대신 구성하세요.

Java

package otel;

import io.opentelemetry.sdk.metrics.Aggregation;
import io.opentelemetry.sdk.metrics.InstrumentSelector;
import io.opentelemetry.sdk.metrics.SdkMeterProvider;
import io.opentelemetry.sdk.metrics.View;

public class OtelHistogramExponentialView {
  static SdkMeterProvider createMeterProvider() {
    // Use a view for per-instrument control — select a specific instrument by name
    // to use exponential histograms while keeping explicit buckets for others.
    return SdkMeterProvider.builder()
        .registerView(
            InstrumentSelector.builder().setName("device.command.duration").build(),
            View.builder().setAggregation(Aggregation.base2ExponentialBucketHistogram()).build())
        .build();
  }
}

Go

func createExponentialView() sdkmetric.View {
	// Use a view for per-instrument control — select a specific instrument by name
	// to use exponential histograms while keeping explicit buckets for others.
	return sdkmetric.NewView(
		sdkmetric.Instrument{Name: "device.command.duration"},
		sdkmetric.Stream{Aggregation: sdkmetric.AggregationBase2ExponentialHistogram{}},
	)
}

Summary

Prometheus Summary는 스크래핑 시 클라이언트 측에서 분위수(quantile)를 계산하고 그것을 라벨이 있는 시계열(예: {quantile="0.95"})로 노출합니다. OpenTelemetry에는 직접적인 동등물이 없습니다.

분위수 추정을 위해 base2 지수 히스토그램이 권장되는 대체물입니다. 버킷 경계를 자동으로 조정해 관찰된 범위를 포괄하고, PromQL의 histogram_quantile()이 쿼리 시점에 경계 오차로 분위수를 계산할 수 있습니다. Summary와 달리 결과는 인스턴스 간에 집계될 수 있습니다. 네이티브 (base2 지수) 히스토그램을 참조하세요.

분위수가 아니라 개수와 합만 필요하다면, 명시적 버킷 경계가 없는 히스토그램이 최소 오버헤드로 그 통계를 포착합니다. 아래 예시는 이 더 단순한 접근 방식을 보여줍니다.

Prometheus (Java)

package otel;

import io.prometheus.metrics.core.metrics.Summary;

public class PrometheusSummary {
  public static void summaryUsage() {
    Summary deviceCommandDuration =
        Summary.builder()
            .name("device_command_duration_seconds")
            .help("Time to receive acknowledgment from a smart home device")
            .labelNames("device_type")
            .quantile(0.5, 0.05)
            .quantile(0.95, 0.01)
            .quantile(0.99, 0.001)
            .register();

    deviceCommandDuration.labelValues("thermostat").observe(0.35);
    deviceCommandDuration.labelValues("lock").observe(0.85);
  }
}

OpenTelemetry (Java)

package otel;

import io.opentelemetry.api.OpenTelemetry;
import io.opentelemetry.api.common.AttributeKey;
import io.opentelemetry.api.common.Attributes;
import io.opentelemetry.api.metrics.DoubleHistogram;
import io.opentelemetry.api.metrics.Meter;
import java.util.List;

public class OtelHistogramAsSummary {
  private static final AttributeKey<String> DEVICE_TYPE = AttributeKey.stringKey("device_type");
  private static final Attributes THERMOSTAT = Attributes.of(DEVICE_TYPE, "thermostat");
  private static final Attributes LOCK = Attributes.of(DEVICE_TYPE, "lock");

  public static void summaryReplacement(OpenTelemetry openTelemetry) {
    Meter meter = openTelemetry.getMeter("smart.home");
    // No explicit bucket boundaries: captures count and sum, a good stand-in for most
    // Summary use cases. For quantile estimation, add boundaries that bracket your thresholds.
    DoubleHistogram deviceCommandDuration =
        meter
            .histogramBuilder("device.command.duration")
            .setDescription("Time to receive acknowledgment from a smart home device")
            .setUnit("s")
            .setExplicitBucketBoundariesAdvice(List.of())
            .build();

    deviceCommandDuration.record(0.35, THERMOSTAT);
    deviceCommandDuration.record(0.85, LOCK);
  }
}

Prometheus (Go)

package main

import "github.com/prometheus/client_golang/prometheus"

var summaryDeviceCommandDuration = prometheus.NewSummaryVec(prometheus.SummaryOpts{
	Name:       "device_command_duration_seconds",
	Help:       "Time to receive acknowledgment from a smart home device",
	Objectives: map[float64]float64{0.5: 0.05, 0.95: 0.01, 0.99: 0.001},
}, []string{"device_type"})

func summaryUsage(reg *prometheus.Registry) {
	reg.MustRegister(summaryDeviceCommandDuration)

	summaryDeviceCommandDuration.WithLabelValues("thermostat").Observe(0.35)
	summaryDeviceCommandDuration.WithLabelValues("lock").Observe(0.85)
}

OpenTelemetry (Go)

package main

import (
	"context"

	"go.opentelemetry.io/otel/attribute"
	"go.opentelemetry.io/otel/metric"
)

// Preallocate attribute options when values are static to avoid per-call allocation.
var (
	summaryThermostatOpts = []metric.RecordOption{metric.WithAttributes(attribute.String("device_type", "thermostat"))}
	summaryLockOpts       = []metric.RecordOption{metric.WithAttributes(attribute.String("device_type", "lock"))}
)

func summaryReplacement(ctx context.Context, meter metric.Meter) {
	// No explicit bucket boundaries: captures count and sum only.
	// For quantile estimation, prefer a base2 exponential histogram instead.
	deviceCommandDuration, err := meter.Float64Histogram("device.command.duration",
		metric.WithDescription("Time to receive acknowledgment from a smart home device"),
		metric.WithUnit("s"),
		metric.WithExplicitBucketBoundaries()) // no boundaries
	if err != nil {
		panic(err)
	}

	deviceCommandDuration.Record(ctx, 0.35, summaryThermostatOpts...)
	deviceCommandDuration.Record(ctx, 0.85, summaryLockOpts...)
}

더 알아보기 (Learn more)