Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 36 additions & 35 deletions docs/observability_guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,20 @@ Application-level logs can tell you when your code called a Google Cloud client,

---

## 2. Dependency Management
## 2. Technical Considerations

### 2.1 Using `libraries-bom` (Recommended)
Before enabling observability, review the following scope and operational considerations:

- **Library Scope**: This guide applies to GAX-based GAPIC client libraries. Handwritten or veneer libraries (such as Spanner, Bigtable, Storage, Pub/Sub, and Firestore) may provide additional or client-specific OpenTelemetry configuration in their respective READMEs.
- **Performance and Overhead**: Recording spans and metrics adds modest per-RPC CPU and memory overhead. In high-throughput production services, use asynchronous batching (`BatchSpanProcessor`) and [OpenTelemetry Sampling](https://opentelemetry.io/docs/concepts/sampling/) to bound overhead.
- **Sensitive Data**: Traces and logs may contain resource names, URLs, or error messages. Review [OpenTelemetry Handling Sensitive Data](https://opentelemetry.io/docs/security/handling-sensitive-data/) before exporting telemetry.
- **Cost**: Exporting telemetry to Google Cloud backends may incur usage costs beyond free tiers. For cost details, see the [Google Cloud Observability pricing page](https://cloud.google.com/stackdriver/pricing).

---

## 3. Dependency Management

### 3.1 Using `libraries-bom` (Recommended)

If your project imports [`com.google.cloud:libraries-bom`](https://central.sonatype.com/artifact/com.google.cloud/libraries-bom), it already manages a compatible version of `opentelemetry-bom` transitively. You do not need to pin OpenTelemetry artifact versions separately — add `opentelemetry-sdk` and the standard OTLP exporter (`opentelemetry-exporter-otlp`) without `<version>` tags:

Expand Down Expand Up @@ -45,7 +56,7 @@ If your project imports [`com.google.cloud:libraries-bom`](https://central.sonat
</dependencies>
```

### 2.2 Managing OpenTelemetry Directly
### 3.2 Managing OpenTelemetry Directly

If you do not use `libraries-bom`, import [`io.opentelemetry:opentelemetry-bom`](https://central.sonatype.com/artifact/io.opentelemetry/opentelemetry-bom) in `<dependencyManagement>` and replace `{{OTEL_LATEST_VERSION}}` with the latest release from Maven Central:

Expand Down Expand Up @@ -79,9 +90,9 @@ If you do not use `libraries-bom`, import [`io.opentelemetry:opentelemetry-bom`]

---

## 3. Distributed Tracing with OpenTelemetry
## 4. Distributed Tracing with OpenTelemetry

### 3.1 Initializing and Enabling Tracing
### 4.1 Initializing and Enabling Tracing

Tracing is disabled by default (`BaseApiTracerFactory`). To enable OpenTelemetry tracing on a client, initialize an `OpenTelemetrySdk` with an OTLP span exporter and register an `OpenTelemetryTracingFactory` on the client's stub settings:

Expand Down Expand Up @@ -111,7 +122,7 @@ settingsBuilder.getStubSettingsBuilder().setTracerFactory(tracingFactory);
MyServiceSettings settings = settingsBuilder.build();
```

### 3.2 Span Hierarchy
### 4.2 Span Hierarchy

When tracing is enabled, GAX instruments client calls with a two-level span hierarchy:

Expand All @@ -120,9 +131,9 @@ When tracing is enabled, GAX instruments client calls with a two-level span hier

---

## 4. Metrics with OpenTelemetry
## 5. Metrics with OpenTelemetry

### 4.1 Enabling Metrics
### 5.1 Enabling Metrics

To emit client-level metrics (such as `gcp.client.request.duration`), configure an `SdkMeterProvider` with an OTLP metric exporter and register an `OpenTelemetryMetricsFactory` on the client's stub settings:

Expand Down Expand Up @@ -152,9 +163,11 @@ settingsBuilder.getStubSettingsBuilder().setTracerFactory(metricsFactory);
MyServiceSettings settings = settingsBuilder.build();
```

### 4.2 Combining Tracing and Metrics (Exemplar Correlation)
### 5.2 Combining Tracing and Metrics (Exemplar Correlation)

To emit both OpenTelemetry spans and client-level metrics with trace exemplars, configure both `SdkTracerProvider` and `SdkMeterProvider` on your `OpenTelemetrySdk` and combine `OpenTelemetryTracingFactory` and `OpenTelemetryMetricsFactory` using `CompositeTracerFactory`:
Metrics provide always-on aggregate signals (such as latency distributions and error rates for dashboards and alerting), while traces provide detailed per-request breakdowns (retries, backoff, and individual wire attempts). Combining both via `CompositeTracerFactory` attaches **trace exemplars** (`trace_id` and `span_id`) to metric histogram buckets, letting you jump directly from a latency spike or error anomaly on a chart into a representative trace for that outlier.

Configure both `SdkTracerProvider` and `SdkMeterProvider` on your `OpenTelemetrySdk` and combine `OpenTelemetryTracingFactory` and `OpenTelemetryMetricsFactory`:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

For completeness and clarity, the sentence should end with 'using CompositeTracerFactory:' to match the style of the previous version of this guide and clearly specify the class used to combine the factories.


```java
import com.google.api.gax.tracing.CompositeTracerFactory;
Expand All @@ -175,17 +188,17 @@ MyServiceSettings settings = settingsBuilder.build();

---

## 5. Structured Logging and Trace Correlation
## 6. Structured Logging and Trace Correlation

### 5.1 Enabling Structured Logging
### 6.1 Enabling Structured Logging

GAX structured and actionable error logging is opt-in. Set the `GOOGLE_SDK_JAVA_LOGGING` environment variable to `true` before starting the JVM:

```bash
export GOOGLE_SDK_JAVA_LOGGING=true
```

### 5.2 SLF4J Binding
### 6.2 SLF4J Binding

GAX and Google Cloud Java libraries log through SLF4J. Include an SLF4J implementation such as [`ch.qos.logback:logback-classic`](https://central.sonatype.com/artifact/ch.qos.logback/logback-classic):

Expand All @@ -197,12 +210,11 @@ GAX and Google Cloud Java libraries log through SLF4J. Include an SLF4J implemen
</dependency>
```

### 5.3 Correlating Logs with Cloud Trace
### 6.3 Correlating Logs with Traces

Google Cloud Java client libraries support two complementary ways to correlate logs with Cloud Trace:
Log correlation works with any OpenTelemetry-compatible trace backend (such as Cloud Trace, Jaeger, or Grafana Tempo) because `trace_id` and `span_id` are read from the standard OpenTelemetry context:

1. **Automatic Context Extraction in Cloud Logging**: When writing logs via `google-cloud-logging` (including the Google Cloud Logging Logback appender), the library inspects the active thread's OpenTelemetry context (`Span.current()`). When a valid span is active, `trace`, `spanId`, and `traceSampled` are automatically populated on the `LogEntry`.
1. **SLF4J Mapped Diagnostic Context (MDC) Propagation**: To include `trace_id` and `span_id` in formatted log output (such as console or file layouts via `%X{trace_id}`), propagate OpenTelemetry context to SLF4J MDC using either:
1. **SLF4J Mapped Diagnostic Context (MDC) Propagation (Any Trace Backend)**: To include `trace_id` and `span_id` in formatted log output (such as console or file layouts via `%X{trace_id}`), propagate OpenTelemetry context to SLF4J MDC using either:
- The [OpenTelemetry Javaagent](https://opentelemetry.io/docs/zero-code/java/agent/), which automatically instruments logging frameworks.
- The [`opentelemetry-logback-mdc-1.0`](https://central.sonatype.com/artifact/io.opentelemetry.instrumentation/opentelemetry-logback-mdc-1.0) dependency:

Expand All @@ -213,26 +225,15 @@ Google Cloud Java client libraries support two complementary ways to correlate l
<version>{{OTEL_INSTRUMENTATION_VERSION}}</version>
</dependency>
```
1. **Automatic Context Extraction in Cloud Logging (Google Cloud)**: When writing logs via `google-cloud-logging` (including the Google Cloud Logging Logback appender), the library automatically inspects the active thread's OpenTelemetry context (`Span.current()`). When a valid span is active, `trace`, `spanId`, and `traceSampled` are populated on the `LogEntry` for correlation with Cloud Trace.

---

## 6. Disabling or Customizing Tracing

Client tracing is disabled by default unless an `OpenTelemetryTracingFactory` is configured. To explicitly disable tracing on a client builder, pass `NoopApiTracerFactory.getInstance()`:
## 7. Viewing Telemetry in Google Cloud

```java
import com.google.api.gax.tracing.NoopApiTracerFactory;
To send OTLP telemetry to Google Cloud and inspect it in the Google Cloud Console:

MyServiceSettings.Builder settingsBuilder = MyServiceSettings.newBuilder();
settingsBuilder.getStubSettingsBuilder().setTracerFactory(NoopApiTracerFactory.getInstance());
MyServiceSettings settings = settingsBuilder.build();
```

---

## 7. Technical Considerations

- **Library Scope**: This guide applies to GAX-based GAPIC client libraries. Handwritten or veneer libraries (such as Spanner, Bigtable, Storage, Pub/Sub, and Firestore) may provide additional or client-specific OpenTelemetry configuration in their respective READMEs.
- **Performance and Overhead**: Recording spans and metrics adds modest per-RPC CPU and memory overhead. In high-throughput production services, use asynchronous batching (`BatchSpanProcessor`) and [OpenTelemetry Sampling](https://opentelemetry.io/docs/concepts/sampling/) to bound overhead.
- **Sensitive Data**: Traces and logs may contain resource names, URLs, or error messages. Review [OpenTelemetry Handling Sensitive Data](https://opentelemetry.io/docs/security/handling-sensitive-data/) before exporting telemetry.
- **Cost**: Exporting telemetry to Google Cloud backends may incur usage costs beyond free tiers. For cost details, see the [Google Cloud Observability pricing page](https://cloud.google.com/stackdriver/pricing).
- **Enable APIs and OTLP Ingestion**: Enable the Telemetry API (`telemetry.googleapis.com`) and configure authentication following the [Google Cloud Telemetry (OTLP) API overview](https://cloud.google.com/stackdriver/docs/reference/telemetry/overview) and [OpenTelemetry instrumentation guide](https://cloud.google.com/stackdriver/docs/instrumentation/overview).
- **Cloud Trace**: Inspect operation and per-attempt span waterfalls in [Cloud Trace Explorer](https://cloud.google.com/trace/docs/finding-traces).
- **Cloud Monitoring**: Chart `gcp.client.request.duration` and click through trace exemplars in [Metrics Explorer](https://cloud.google.com/monitoring/charts/metrics-explorer).
- **Cloud Logging**: View structured actionable error logs correlated with trace IDs in [Logs Explorer](https://cloud.google.com/logging/docs/view/logs-explorer-interface).
Loading