OpenCensus로 사용자 정의 측정항목 만들기

OpenCensus는 무료 오픈소스 프로젝트로, 라이브러리에서

  • 여러 언어로 측정항목 및 trace 데이터 수집에 대한 공급업체 중립적인 지원을 제공합니다.
  • 수집된 데이터를 내보내기를 사용하여 Cloud Monitoring을 포함한 다양한 백엔드 애플리케이션으로 내보낼 수 있습니다.

Cloud Monitoring이 사용자 정의 측정항목을 정의하고 수집하는 API를 제공하긴 하지만 이는 낮은 수준의 독점 API입니다. OpenCensus는 Monitoring API를 통해 훨씬 자연스러운 API를 제공할 뿐만 아니라 Cloud Monitoring에 측정항목을 전송하는 내보내기를 제공합니다.

OpenCensus는 애플리케이션 추적 기능도 훌륭히 지원합니다. 이에 대한 정보는 OpenCensus Tracing을 참조하세요. Cloud Trace는 OpenCensus를 사용하여 추적을 수행하도록 권장합니다. 서비스에서 측정항목 및 trace 데이터를 모두 수집하려면 단일 라이브러리 분산을 사용하면 됩니다. Cloud Trace에서 OpenCensus 사용에 대한 자세한 내용은 Trace용 클라이언트 라이브러리를 참조하세요.

시작하기 전에

Cloud Monitoring을 사용하려면 결제가 사용 설정된 Google Cloud 프로젝트가 있어야 합니다. 필요한 경우 다음을 수행합니다.

  1. Google Cloud Console의 프로젝트 선택기 페이지에서 Google Cloud 프로젝트를 선택하거나 만듭니다.

    프로젝트 선택기로 이동

  2. Google Cloud 프로젝트에 결제가 사용 설정되어 있는지 확인합니다.

  3. Monitoring API가 사용 설정되어 있는지 확인합니다. 자세한 내용은 Monitoring API 사용 설정을 참조하세요.
  4. Google Cloud 외부에서 실행되는 애플리케이션의 경우 Google Cloud 프로젝트가 애플리케이션을 인증해야 합니다. 일반적으로 프로젝트의 서비스 계정을 만들고 환경 변수를 구성하여 인증을 설정합니다.

    Amazon Elastic Compute Cloud(Amazon EC2) 인스턴스에서 실행되는 애플리케이션의 경우 인스턴스의 AWS 커넥터 프로젝트에 대한 서비스 계정을 만듭니다.

    서비스 계정 만들기에 대한 자세한 내용은 인증 시작하기를 참조하세요.

OpenCensus 설치

Google Cloud 프로젝트에서 OpenCensus로 수집된 측정항목을 사용하려면 OpenCensus 측정항목 라이브러리 및 Stackdriver 내보내기 도구를 애플리케이션에 제공해야 합니다. Stackdriver 내보내기 도구는 OpenCensus가 수집하는 측정항목을 Google Cloud 프로젝트로 내보냅니다. 그런 후 Cloud Monitoring을 사용하여 이러한 측정항목을 차트로 작성하거나 모니터링할 수 있습니다.

Go

BigQuery에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

OpenCensus를 사용하려면 Go 버전 1.11 이상이 필요합니다. 종속 항목은 자동으로 처리됩니다.

Java

BigQuery에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

Maven을 사용하는 경우 pom.xml 파일의 dependencies 요소에 다음을 추가합니다.
<dependency>
  <groupId>io.opencensus</groupId>
  <artifactId>opencensus-api</artifactId>
  <version>${opencensus.version}</version>
</dependency>
<dependency>
  <groupId>io.opencensus</groupId>
  <artifactId>opencensus-exporter-stats-stackdriver</artifactId>
  <version>${opencensus.version}</version>
</dependency>

Node.js

Monitoring에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

  1. OpenCensus 코어 및 내보내기 라이브러리를 설치하기 전에 Node.js 개발을 위한 환경이 준비되었는지 확인합니다.
  2. OpenCensus를 설치하는 가장 쉬운 방법은 npm을 사용하는 것입니다.
    npm install @opencensus/core
    npm install @opencensus/exporter-stackdriver
  3. 다음과 같이 애플리케이션의 기본 스크립트 맨 위 또는 진입점에 표시된 require 문을 다른 모든 코드 앞에 배치합니다.
const {globalStats, MeasureUnit, AggregationType} = require('@opencensus/core');
const {StackdriverStatsExporter} = require('@opencensus/exporter-stackdriver');

Python

Monitoring에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

다음 명령어를 사용하여 OpenCensus 코어 및 Stackdriver 내보내기 라이브러리를 설치합니다.

pip install -r opencensus/requirements.txt

requirements.txt 파일은 python-docs-samples 샘플의 GitHub 저장소에 있습니다.

OpenCensus로 사용자 정의 측정항목 쓰기

측정항목에 OpenCensus를 사용하기 위한 코드를 설치하려면 다음 3단계를 거칩니다.

  1. OpenCensus 통계와 OpenCensus Stackdriver 내보내기 도구 패키지를 불러옵니다.
  2. Stackdriver 내보내기 도구를 초기화합니다.
  3. OpenCensus API를 사용하여 코드를 설치합니다.

다음 예시는 OpenCensus를 사용하여 측정항목 데이터를 작성하는 최소한의 프로그램입니다. 이 프로그램은 루프를 실행하고 지연 시간 값을 수집하며 루프가 끝나면 Cloud Monitoring으로 통계를 내보내고 종료합니다.

Go

BigQuery에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


// metrics_quickstart is an example of exporting a custom metric from
// OpenCensus to Stackdriver.
package main

import (
	"context"
	"fmt"
	"log"
	"time"

	"contrib.go.opencensus.io/exporter/stackdriver"
	"go.opencensus.io/stats"
	"go.opencensus.io/stats/view"
	"golang.org/x/exp/rand"
)

var (
	// The task latency in milliseconds.
	latencyMs = stats.Float64("task_latency", "The task latency in milliseconds", "ms")
)

func main() {
	ctx := context.Background()

	// Register the view. It is imperative that this step exists,
	// otherwise recorded metrics will be dropped and never exported.
	v := &view.View{
		Name:        "task_latency_distribution",
		Measure:     latencyMs,
		Description: "The distribution of the task latencies",

		// Latency in buckets:
		// [>=0ms, >=100ms, >=200ms, >=400ms, >=1s, >=2s, >=4s]
		Aggregation: view.Distribution(0, 100, 200, 400, 1000, 2000, 4000),
	}
	if err := view.Register(v); err != nil {
		log.Fatalf("Failed to register the view: %v", err)
	}

	// Enable OpenCensus exporters to export metrics
	// to Stackdriver Monitoring.
	// Exporters use Application Default Credentials to authenticate.
	// See https://developers.google.com/identity/protocols/application-default-credentials
	// for more details.
	exporter, err := stackdriver.NewExporter(stackdriver.Options{})
	if err != nil {
		log.Fatal(err)
	}
	// Flush must be called before main() exits to ensure metrics are recorded.
	defer exporter.Flush()

	if err := exporter.StartMetricsExporter(); err != nil {
		log.Fatalf("Error starting metric exporter: %v", err)
	}
	defer exporter.StopMetricsExporter()

	// Record 100 fake latency values between 0 and 5 seconds.
	for i := 0; i < 100; i++ {
		ms := float64(5*time.Second/time.Millisecond) * rand.Float64()
		fmt.Printf("Latency %d: %f\n", i, ms)
		stats.Record(ctx, latencyMs.M(ms))
		time.Sleep(1 * time.Second)
	}

	fmt.Println("Done recording metrics")
}

Java

Monitoring에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


import com.google.common.collect.Lists;
import io.opencensus.exporter.stats.stackdriver.StackdriverStatsExporter;
import io.opencensus.stats.Aggregation;
import io.opencensus.stats.BucketBoundaries;
import io.opencensus.stats.Measure.MeasureLong;
import io.opencensus.stats.Stats;
import io.opencensus.stats.StatsRecorder;
import io.opencensus.stats.View;
import io.opencensus.stats.View.Name;
import io.opencensus.stats.ViewManager;
import java.io.IOException;
import java.util.Collections;
import java.util.Random;
import java.util.concurrent.TimeUnit;

public class Quickstart {
  private static final int EXPORT_INTERVAL = 70;
  private static final MeasureLong LATENCY_MS =
      MeasureLong.create("task_latency", "The task latency in milliseconds", "ms");
  // Latency in buckets:
  // [>=0ms, >=100ms, >=200ms, >=400ms, >=1s, >=2s, >=4s]
  private static final BucketBoundaries LATENCY_BOUNDARIES =
      BucketBoundaries.create(Lists.newArrayList(0d, 100d, 200d, 400d, 1000d, 2000d, 4000d));
  private static final StatsRecorder STATS_RECORDER = Stats.getStatsRecorder();

  public static void main(String[] args) throws IOException, InterruptedException {
    // Register the view. It is imperative that this step exists,
    // otherwise recorded metrics will be dropped and never exported.
    View view =
        View.create(
            Name.create("task_latency_distribution"),
            "The distribution of the task latencies.",
            LATENCY_MS,
            Aggregation.Distribution.create(LATENCY_BOUNDARIES),
            Collections.emptyList());

    ViewManager viewManager = Stats.getViewManager();
    viewManager.registerView(view);

    // Enable OpenCensus exporters to export metrics to Stackdriver Monitoring.
    // Exporters use Application Default Credentials to authenticate.
    // See https://developers.google.com/identity/protocols/application-default-credentials
    // for more details.
    StackdriverStatsExporter.createAndRegister();

    // Record 100 fake latency values between 0 and 5 seconds.
    Random rand = new Random();
    for (int i = 0; i < 100; i++) {
      long ms = (long) (TimeUnit.MILLISECONDS.convert(5, TimeUnit.SECONDS) * rand.nextDouble());
      System.out.println(String.format("Latency %d: %d", i, ms));
      STATS_RECORDER.newMeasureMap().put(LATENCY_MS, ms).record();
    }

    // The default export interval is 60 seconds. The thread with the StackdriverStatsExporter must
    // live for at least the interval past any metrics that must be collected, or some risk being
    // lost if they are recorded after the last export.

    System.out.println(
        String.format(
            "Sleeping %d seconds before shutdown to ensure all records are flushed.",
            EXPORT_INTERVAL));
    Thread.sleep(TimeUnit.MILLISECONDS.convert(EXPORT_INTERVAL, TimeUnit.SECONDS));
  }
}

Node.js

Monitoring에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

'use strict';

const {globalStats, MeasureUnit, AggregationType} = require('@opencensus/core');
const {StackdriverStatsExporter} = require('@opencensus/exporter-stackdriver');

const EXPORT_INTERVAL = process.env.EXPORT_INTERVAL || 60;
const LATENCY_MS = globalStats.createMeasureInt64(
  'task_latency',
  MeasureUnit.MS,
  'The task latency in milliseconds'
);

// Register the view. It is imperative that this step exists,
// otherwise recorded metrics will be dropped and never exported.
const view = globalStats.createView(
  'task_latency_distribution',
  LATENCY_MS,
  AggregationType.DISTRIBUTION,
  [],
  'The distribution of the task latencies.',
  // Latency in buckets:
  // [>=0ms, >=100ms, >=200ms, >=400ms, >=1s, >=2s, >=4s]
  [0, 100, 200, 400, 1000, 2000, 4000]
);

// Then finally register the views
globalStats.registerView(view);

// Enable OpenCensus exporters to export metrics to Stackdriver Monitoring.
// Exporters use Application Default Credentials (ADCs) to authenticate.
// See https://developers.google.com/identity/protocols/application-default-credentials
// for more details.
// Expects ADCs to be provided through the environment as ${GOOGLE_APPLICATION_CREDENTIALS}
// A Stackdriver workspace is required and provided through the environment as ${GOOGLE_PROJECT_ID}
const projectId = process.env.GOOGLE_PROJECT_ID;

// GOOGLE_APPLICATION_CREDENTIALS are expected by a dependency of this code
// Not this code itself. Checking for existence here but not retaining (as not needed)
if (!projectId || !process.env.GOOGLE_APPLICATION_CREDENTIALS) {
  throw Error('Unable to proceed without a Project ID');
}

// The minimum reporting period for Stackdriver is 1 minute.
const exporter = new StackdriverStatsExporter({
  projectId: projectId,
  period: EXPORT_INTERVAL * 1000,
});

// Pass the created exporter to Stats
globalStats.registerExporter(exporter);

// Record 100 fake latency values between 0 and 5 seconds.
for (let i = 0; i < 100; i++) {
  const ms = Math.floor(Math.random() * 5);
  console.log(`Latency ${i}: ${ms}`);
  globalStats.record([
    {
      measure: LATENCY_MS,
      value: ms,
    },
  ]);
}

/**
 * The default export interval is 60 seconds. The thread with the
 * StackdriverStatsExporter must live for at least the interval past any
 * metrics that must be collected, or some risk being lost if they are recorded
 * after the last export.
 */
setTimeout(() => {
  console.log('Done recording metrics.');
  globalStats.unregisterExporter(exporter);
}, EXPORT_INTERVAL * 1000);

Python

Monitoring에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


from random import random
import time

from opencensus.ext.stackdriver import stats_exporter
from opencensus.stats import aggregation
from opencensus.stats import measure
from opencensus.stats import stats
from opencensus.stats import view

# A measure that represents task latency in ms.
LATENCY_MS = measure.MeasureFloat(
    "task_latency", "The task latency in milliseconds", "ms"
)

# A view of the task latency measure that aggregates measurements according to
# a histogram with predefined bucket boundaries. This aggregate is periodically
# exported to Stackdriver Monitoring.
LATENCY_VIEW = view.View(
    "task_latency_distribution",
    "The distribution of the task latencies",
    [],
    LATENCY_MS,
    # Latency in buckets: [>=0ms, >=100ms, >=200ms, >=400ms, >=1s, >=2s, >=4s]
    aggregation.DistributionAggregation([100.0, 200.0, 400.0, 1000.0, 2000.0, 4000.0]),
)

def main():
    # Register the view. Measurements are only aggregated and exported if
    # they're associated with a registered view.
    stats.stats.view_manager.register_view(LATENCY_VIEW)

    # Create the Stackdriver stats exporter and start exporting metrics in the
    # background, once every 60 seconds by default.
    exporter = stats_exporter.new_stats_exporter()
    print('Exporting stats to project "{}"'.format(exporter.options.project_id))

    # Register exporter to the view manager.
    stats.stats.view_manager.register_exporter(exporter)

    # Record 100 fake latency values between 0 and 5 seconds.
    for num in range(100):
        ms = random() * 5 * 1000

        mmap = stats.stats.stats_recorder.new_measurement_map()
        mmap.measure_float_put(LATENCY_MS, ms)
        mmap.record()

        print(f"Fake latency recorded ({num}: {ms})")

    # Keep the thread alive long enough for the exporter to export at least
    # once.
    time.sleep(65)

if __name__ == "__main__":
    main()
이 측정항목 데이터를 Cloud Monitoring으로 내보낼 때 다른 데이터와 마찬가지로 사용할 수 있습니다.

이 프로그램은 task_latency_distribution이라는 OpenCensus 보기를 만듭니다. 이 문자열은 Cloud Monitoring으로 내보낼 때 측정항목 이름의 일부가 됩니다. OpenCensus 보기가 Cloud Monitoring 측정항목 설명으로 구현되는 방법을 보려면 측정항목 설명 검색을 참조하세요. 따라서 차트에서 측정항목을 선택할 때 보기 이름을 검색 문자열로 사용할 수 있습니다.

샘플 프로그램을 실행하면 측정항목 탐색기로 데이터를 볼 수 있습니다.
  1. Google Cloud 콘솔의 탐색 패널에서 Monitoring을 선택한 후 측정항목 탐색기를 선택합니다.

    측정항목 탐색기로 이동

  2. 측정항목 요소에서 측정항목 선택 메뉴를 펼치고 필터 표시줄에 OpenCensus/task_latency_distribution을 입력한 후 하위 메뉴를 사용하여 특정 리소스 유형과 측정항목을 선택합니다.
    1. 활성 리소스 메뉴에서 모니터링 리소스를 선택합니다. 로컬 환경에서 프로그램을 실행하는 경우 전역을 사용합니다.
    2. 활성 측정항목 카테고리 메뉴에서 커스텀을 선택합니다.
    3. 활성 측정항목 메뉴에서 태스크 지연 시간 분포를 선택합니다.
    4. 적용을 클릭합니다.

다음 스크린샷은 로컬 환경에서 프로그램을 실행한 후 수집된 시계열을 보여줍니다.

Cloud Monitoring의 OpenCensus에서 가져온 측정항목

히트맵의 각 줄은 프로그램 1회 실행을, 각 줄의 색상 요소는 지연 시간 분배 버킷을 나타냅니다.

Cloud Monitoring에서 OpenCensus 측정항목 읽기

기본 제공 측정항목과 같이 OpenCensus에서 작성한 측정항목을 포함하여 사용자 정의 측정항목을 사용합니다. 차트를 작성하고, 여기에 경고를 설정하고, 이를 읽거나 모니터링할 수 있습니다.

이 섹션에서는 API 탐색기를 사용하여 측정항목 데이터를 읽는 방법을 보여줍니다. Cloud Monitoring API 또는 클라이언트 라이브러리를 사용하여 측정항목 데이터를 읽는 방법은 다음 문서를 참조하세요.

예를 들어 이전 섹션에 표시된 스크린샷은 측정항목 탐색기의 스크린샷입니다. 차트 도구를 사용할 때는 OpenCensus 보기 이름을 사용하여 측정항목 목록을 필터링하는 것이 좋습니다. 자세한 내용은 측정항목 탐색기 사용 시 측정항목 선택을 참조하세요.

측정항목 설명 검색

Monitoring API를 직접 사용하여 측정항목 데이터를 검색하려면 OpenCensus 측정항목을 내보낸 Cloud Monitoring 이름을 알아야 합니다. 내보내기 도구로 만든 측정항목 설명을 검색한 후 type 필드를 확인하여 이러한 이름을 확인할 수 있습니다. 측정항목 설명에 대한 자세한 내용은 MetricDescriptor를 참조하세요.

내보낸 측정항목에 대해 생성된 측정항목 설명을 보려면 다음을 수행합니다.

  1. metricDescriptors.list 참조 페이지로 이동하세요.
  2. 참조 페이지의 API 사용해 보기 위젯에서 다음 필드를 작성합니다.

    1. name 필드에 프로젝트 이름을 입력합니다. 다음 이름 구조 projects/PROJECT_ID를 사용하세요. 이 문서에서는 ID가 a-gcp-project인 프로젝트가 사용됩니다.

    2. filter 필드에 필터를 입력합니다. 프로젝트에는 측정항목 설명이 많습니다. 필터링을 사용하면 원하지 않는 설명을 제거할 수 있습니다.

      예를 들어 OpenCensus 보기 이름이 측정항목 이름에 포함되므로, 다음과 같은 필터를 추가할 수 있습니다.

      metric.type=has_substring("task_latency_distribution")

      metric.type 키는 시계열에 삽입된 유형의 필드를 나타냅니다. 자세한 내용은 TimeSeries를 참조하세요.

    3. 실행을 클릭합니다.

다음은 반환된 측정항목 설명자를 나타냅니다.

    {
      "metricDescriptors": [
        {
          "name": "projects/a-gcp-project/metricDescriptors/custom.googleapis.com/opencensus/task_latency_distribution",
          "labels": [
            {
              "key": "opencensus_task",
              "description": "Opencensus task identifier"
            }
          ],
          "metricKind": "CUMULATIVE",
          "valueType": "DISTRIBUTION",
          "unit": "ms",
          "description": "The distribution of the task latencies",
          "displayName": "OpenCensus/task_latency_distribution",
          "type": "custom.googleapis.com/opencensus/task_latency_distribution"
        }
      ]
    }

측정항목 설명의 이 줄은 Cloud Monitoring에서 측정항목 유형의 이름을 알려줍니다.

    "type": "custom.googleapis.com/opencensus/task_latency_distribution"

이제 측정항목 유형과 관련된 데이터를 수동으로 검색하는 데 필요한 정보가 준비되었습니다. type 필드 값은 측정항목을 차트로 작성할 때도 Google Cloud 콘솔에 표시됩니다.

측정항목 데이터 검색

측정항목 유형에서 시계열 데이터를 수동으로 검색하려면 다음을 수행합니다.

  1. timeSeries.list 참조 페이지로 이동하세요.
  2. 참조 페이지의 API 사용해 보기 위젯에서 다음 필드를 작성합니다.

    1. name 필드에 프로젝트 이름을 입력합니다. 다음 이름 구조 projects/PROJECT_ID를 사용하세요.
    2. filter 필드에 다음 값을 입력합니다.

      metric.type="custom.googleapis.com/opencensus/task_latency_distribution"

    3. interval.startTimeinterval.endTime 필드의 값을 입력합니다. 이러한 값은 2018-10-11T15:48:38-04:00와 같이 타임스탬프로 입력해야 합니다. startTime 값이 endTime 값보다 이전인지 확인합니다.

    4. 실행 버튼을 클릭합니다.

다음은 위와 같이 검색한 결과입니다.

    {
      "timeSeries": [
        {
          "metric": {
            "labels": {
              "opencensus_task": "java-3424@docbuild"
            },
            "type": "custom.googleapis.com/opencensus/task_latency_distribution"
          },
          "resource": {
            "type": "gce_instance",
            "labels": {
              "instance_id": "2455918024984027105",
              "zone": "us-east1-b",
              "project_id": "a-gcp-project"
            }
          },
          "metricKind": "CUMULATIVE",
          "valueType": "DISTRIBUTION",
          "points": [
            {
              "interval": {
                "startTime": "2019-04-04T17:49:34.163Z",
                "endTime": "2019-04-04T17:50:42.917Z"
              },
              "value": {
                "distributionValue": {
                  "count": "100",
                  "mean": 2610.11,
                  "sumOfSquaredDeviation": 206029821.78999996,
                  "bucketOptions": {
                    "explicitBuckets": {
                      "bounds": [
                        0,
                        100,
                        200,
                        400,
                        1000,
                        2000,
                        4000
                      ]
                    }
                  },
                  "bucketCounts": [
                    "0",
                    "0",
                    "1",
                    "6",
                    "13",
                    "15",
                    "44",
                    "21"
                  ]
                }
              }
            }
          ]
        },
        [ ... data from additional program runs deleted ...]
      ]
    }

반환된 측정항목 데이터에는 다음이 포함됩니다.

  • 데이터가 수집된 모니터링 리소스 정보 OpenCensus는 gce_instance, k8s_container, aws_ec2_instance 모니터링 리소스를 자동으로 감지할 수 있습니다. Compute Engine 인스턴스에서 실행되는 프로그램에서 이 데이터를 가져옵니다. 다른 모니터링 리소스 사용에 대한 자세한 내용은 내보내기에 모니터링 리소스 설정을 참조하세요.
  • 측정항목 종류와 값 유형에 대한 설명
  • 요청된 시간 간격 내에서 수집된 실제 데이터 포인트

Monitoring이 OpenCensus 측정항목을 나타내는 방법

사용자 정의 측정항목에 대해 Cloud Monitoring API 직접 사용이 지원됩니다. 사용 방법은 API로 사용자 정의 측정항목 만들기를 참조하세요. 실제로 Cloud Monitoring의 OpenCensus 내보내기에서 이 API를 사용합니다. 이 섹션에서는 Cloud Monitoring이 OpenCensus로 작성된 측정항목을 표현하는 방법에 대한 몇 가지 정보를 제공합니다.

OpenCensus API에서 사용하는 구문은 Cloud Monitoring에서 사용하는 구문과 다르며, 일부 용어의 사용에도 차이가 있습니다. Cloud Monitoring이 '측정항목'을 참조하는 경우 OpenCensus는 '통계'를 의미합니다. 예를 들어 Cloud Monitoring에 측정항목 데이터를 전송하는 OpenCensus 구성요소를 'Stackdrdiver의 통계 내보내기'라고 합니다.

측정항목에 대한 OpenCensus 모델 개요는 OpenCensus 측정항목을 참조하세요.

OpenCensus 통계 및 Cloud Monitoring 측정항목의 데이터 모델은 1:1로 깔끔하게 매핑되지 않습니다. 동일한 개념도 다수 존재하긴 하지만 서로 바꾸어 사용할 수는 없습니다.

  • OpenCensus 는 Monitoring API의 MetricDescriptor와 유사합니다. 뷰는 개별 측정 값을 수집하고 집계하는 방법을 설명합니다. 태그는 기록된 모든 측정 값에 포함됩니다.

  • OpenCensus 태그는 키-값 쌍입니다. OpenCensus 태그는 일반적으로 Monitoring API의 LabelDescriptor에 해당합니다. 태그를 사용하면 측정항목을 필터링하고 그룹화하는 데 사용할 수 있는 컨텍스트 정보를 캡처할 수 있습니다.

  • OpenCensus 측정 값은 기록할 측정항목 데이터를 설명합니다. OpenCensus 집계는 요약 데이터에 적용되는 기능입니다. 이 기능은 내보내기에 사용되어 Cloud Monitoring 측정항목 설명에 보고된 MetricKind, ValueType, 단위를 결정합니다.

  • OpenCensus 측정 값은 수집된 데이터 포인트입니다. 측정 값은 보기로 집계되어야 합니다. 그렇지 않으면 개별 측정 값이 삭제됩니다. OpenCensus 측정 값은 Monitoring API의 Point와 유사합니다. 뷰에서 측정 값이 집계되면 수집 데이터는 Monitoring API의 TimeSeries와 유사한 뷰 데이터로 저장됩니다.

다음 단계