Installation

Install as Agent Plugin Recommended
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install app-observability@skills-hub

Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled). Plugin app-observability v1.0.0 follows the Agent Plugins spec.

Install with the gh extension
gh skills-hub install app-observability

Don't have the extension? Run gh extension install samueltauil/skills-hub first.

Download and extract to your repository:

.github/skills/app-observability/

Extract the ZIP to .github/skills/ in your repo. The folder name must match app-observability for Copilot to auto-discover it.

Skill Files (6)

SKILL.md 7.2 KB
---
name: app-observability
license: Apache-2.0
description: Get RED metrics + service maps + frontend RUM + AI/LLM monitoring out of Grafana Cloud — Application Observability (`traces_spanmetrics_*` from OTel traces, p50/p95/p99 latency, exemplar-to-trace, traces-to-logs / profiles), Frontend Observability with the Faro Web SDK (Core Web Vitals, session replay, `pushError`, React + router integration, `TracingInstrumentation` for browser → backend trace correlation), and AI Observability via OpenLIT (token / cost / latency, GPU, hallucination + toxicity evals). Use when standing up APM for a service, wiring an Alloy OTLP receiver + forwarding to Cloud, instrumenting a React frontend for RUM, debugging why service-map edges are missing, monitoring LLM cost drift, or correlating a frontend error to its backend trace — even when the user says "set up APM", "show service map", "monitor browser perf", "session replay", "RUM SDK", or "watch our OpenAI bill" without naming App / Frontend / AI Observability.
---

# Grafana Cloud Application Observability

> **Docs**: https://grafana.com/docs/grafana-cloud/monitor-applications/

Three products that share the same OTLP + Mimir / Loki / Tempo / Pyroscope plumbing:

1. **Application Observability** — APM from OTel spanmetrics
2. **Frontend Observability** — Faro Web SDK, RUM + session replay
3. **AI Observability** — LLM / vector-DB monitoring via OpenLIT

## Prerequisites

- Grafana Cloud stack + OTLP endpoint + numeric instance ID + API key with `MetricsPublisher` + `LogsPublisher` + `TracesPublisher`
- For APM: app instrumented with OTel SDK; for Frontend: a web app + Faro app key; for AI: Python ≥ 3.10
- Grafana Alloy as the local OTLP receiver (recommended)

## Common Workflows

### 1. Stand up APM — Alloy receiver → Grafana Cloud + verify

```bash
# 1. Set Cloud creds + start Alloy with config from references/apm.md
export GRAFANA_CLOUD_OTLP_ENDPOINT=https://otlp-gateway-prod-us-east-0.grafana.net/otlp
export GRAFANA_CLOUD_INSTANCE_ID=123456
export GRAFANA_CLOUD_API_KEY=glc_eyJ...
alloy fmt /etc/alloy/config.alloy   # syntax check
alloy run /etc/alloy/config.alloy

# 2. Verify Alloy is receiving + forwarding
curl -s http://localhost:12345/api/v0/web/components \
  | jq '.[] | select(.id|test("otelcol\\.exporter\\.otlphttp"))
        | {id, health:.health.state}'
# Expect health.state == "healthy"
curl -s http://localhost:12345/metrics \
  | grep -E 'otelcol_(receiver_accepted_spans|exporter_sent_spans)'

# 3. Point your app at Alloy (with required attributes!)
export OTEL_SERVICE_NAME="my-api"
export OTEL_RESOURCE_ATTRIBUTES="service.namespace=myteam,deployment.environment=production"
export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317
export OTEL_EXPORTER_OTLP_PROTOCOL=grpc

# 4. Verify spans landed in Tempo + spanmetrics generated
#    Tempo (TraceQL):  { resource.service.name = "my-api" }
#    Mimir (PromQL):   sum by (job) (rate(traces_spanmetrics_calls_total{service_name="my-api"}[5m]))
#    Expect > 0 within ~1 minute.

# 5. Verify it's wired to App Observability
#    Grafana → Application → Service Inventory: "my-api" should appear with RED metrics
#    Click into it → Service Map edges visible (requires span.kind on outbound calls)
```

Full Alloy block + required resource attributes + spanmetric names + correlation links: [`references/apm.md`](references/apm.md).

### 2. Instrument a React frontend with Faro

```bash
# 1. Install
npm install @grafana/faro-react @grafana/faro-web-tracing
```

```javascript
// 2. initializeFaro with TracingInstrumentation + ReactIntegration (see references/faro.md)
//    Push a smoketest event so we have a known signal:
faro.api.pushEvent('faro_smoketest', { ts: Date.now().toString() });
```

```bash
# 3. Verify in DevTools Network — POST to /collect returns 202
#    (401 → wrong app key; 404 → wrong url region)

# 4. Verify in Grafana Cloud
#    - Frontend Observability → your app → Sessions: your session appears
#    - LogQL on Loki: {kind="event"} |= "faro_smoketest"
#    - With TracingInstrumentation: open the session → the trace ID links to Tempo
```

Full React example, CDN setup, session config: [`references/faro.md`](references/faro.md).

### 3. Add AI / LLM observability

```bash
pip install openlit==1.42.0
```

```python
# At app startup
import openlit
openlit.init(application_name="my-ai-app", environment="production")
# Your existing OpenAI / Anthropic / Cohere calls now emit OTel spans + metrics.
```

```bash
# Env (same OTLP endpoint as APM)
export OTEL_SERVICE_NAME="my-ai-app"
export OTEL_EXPORTER_OTLP_ENDPOINT="https://otlp-gateway-<region>.grafana.net/otlp"
export OTEL_EXPORTER_OTLP_HEADERS="Authorization=Basic $(echo -n $ID:$KEY | base64)"

# Verify after a few LLM calls:
#   PromQL: sum by (gen_ai_request_model) (rate(gen_ai_usage_input_tokens_total[5m]))
#   Dashboard: Grafana → AI Observability → "GenAI Observability" auto-populates
```

Full OpenLIT install, evals/guards, GenAI metric list, dashboard names: [`references/ai-observability.md`](references/ai-observability.md).

## Full-stack correlation cheat sheet

| Signal | Product | Storage | Query |
|---|---|---|---|
| RED metrics | App Observability | Mimir | PromQL |
| Traces | Tempo | Tempo | TraceQL |
| Logs | Loki | Loki | LogQL |
| Profiles | Pyroscope | Pyroscope | ProfileQL |
| Browser RUM | Frontend Observability | Loki + Tempo | LogQL / TraceQL |
| LLM metrics | AI Observability | Mimir | PromQL |

Correlation keys: `service.name` joins all signals; trace exemplars embed trace IDs in metric points; `traceID` in logs and `traceparent` injected by Faro for FE → BE linking.

## Troubleshooting

- Service missing from Service Inventory → missing `service.namespace` (job label) or `deployment.environment` resource attribute
- Service Map edges missing → `span.kind` not set on outbound calls (must be CLIENT) or inbound (SERVER)
- Faro `/collect` returns 401 → wrong app key; 404 → region in URL doesn't match the Faro app
- No GenAI metrics → confirm OpenLIT version matches OTel semantic-conv version expected by Cloud; verify auth with curl as in workflow #3

## References

- [`references/apm.md`](references/apm.md) — APM essentials: how RED metrics are generated, required OTel resource attributes, Alloy config, correlation links
- [`references/apm-setup.md`](references/apm-setup.md) — deep dive: full per-language OTel SDK setup (Node / Python / Java / Go), span-metrics options, complete Alloy config
- [`references/faro.md`](references/faro.md) — Faro essentials: SDK init, instrumentations, session replay
- [`references/frontend-observability.md`](references/frontend-observability.md) — deep dive: full Faro SDK reference, React/Vue/Angular integration, custom events, source maps
- [`references/ai-observability.md`](references/ai-observability.md) — OpenLIT auto-instrumentation for OpenAI / Anthropic / Bedrock / Vertex AI

## Resources

- [App Observability docs](https://grafana.com/docs/grafana-cloud/monitor-applications/application-observability/)
- [Frontend Observability docs](https://grafana.com/docs/grafana-cloud/monitor-applications/frontend-observability/)
- [Faro Web SDK](https://github.com/grafana/faro-web-sdk)
- [AI Observability docs](https://grafana.com/docs/grafana-cloud/monitor-applications/ai-observability/)
- [OpenLIT](https://openlit.io/)
references/
ai-observability.md 2.4 KB
# AI Observability — LLM / model monitoring

Built on OTel GenAI semantic conventions + OpenLIT.

## What it monitors

- LLM API calls (OpenAI, Anthropic, Cohere, Google, etc.)
- Vector DBs (Pinecone, Weaviate, Chroma, …)
- AI frameworks (LangChain, CrewAI, LlamaIndex)
- Model Context Protocol (MCP) servers
- GPU utilization
- Evaluation quality (hallucination, toxicity, bias)

## Key metrics (OTel GenAI)

| Metric | Description |
|---|---|
| `gen_ai_usage_input_tokens_total` | Input / prompt tokens |
| `gen_ai_usage_output_tokens_total` | Output / completion tokens |
| `gen_ai_usage_cost_USD_sum` | Total USD cost |
| `gen_ai_client_operation_duration` | Per-call latency histogram |
| `gen_ai_client_token_usage` | Token-usage histogram |

Trace spans capture `gen_ai.request.model`, temperature/top_p, prompts/completions (configurable), `gen_ai.system`, time-to-first-token.

## Python install + init

```bash
pip install openlit==1.42.0 openai==2.41.0 anthropic==0.105.2 cohere==7.0.3
```

```python
import openlit
openlit.init(application_name="my-ai-app", environment="production")

# Existing LLM code works unchanged
import openai
client = openai.OpenAI()
client.chat.completions.create(
    model="gpt-4", messages=[{"role":"user","content":"Hello!"}])
```

## OTel env vars

```bash
export OTEL_SERVICE_NAME="my-ai-app"
export OTEL_DEPLOYMENT_ENVIRONMENT="production"
export OTEL_EXPORTER_OTLP_ENDPOINT="https://otlp-gateway-<region>.grafana.net/otlp"
# Basic auth: base64(instanceID:apiToken)
export OTEL_EXPORTER_OTLP_HEADERS="Authorization=Basic <base64>"
```

Credentials: **My Account → Stack → OpenTelemetry**.

## Evals + guards

```python
evals = openlit.evals.Hallucination(provider="openai", api_key=os.getenv("OPENAI_API_KEY"))
evals.measure(prompt=user_message, contexts=["..."], text=llm_answer)

guard = openlit.guard.All(provider="openai", api_key=os.getenv("OPENAI_API_KEY"))
guard.detect(text=user_message)
```

## Pre-built dashboards (auto-populated)

1. GenAI Observability — rates, latency percentiles, costs
2. GenAI Evaluations — hallucination / bias / toxicity scores
3. Vector Database Observability
4. MCP Observability
5. GPU Monitoring

## Setup

1. Cloud → **Connections** → "AI Observability"
2. UI wizard → OTLP endpoint + API key
3. Set env vars
4. `pip install openlit==1.42.0` + `openlit.init()` at app startup
5. Deploy — dashboards populate within minutes
apm-setup.md 23.1 KB
# Grafana Cloud Application Observability - APM Setup Reference

## Overview

Application Observability is Grafana Cloud's pre-built APM (Application Performance Monitoring) product. It requires:

1. Applications instrumented with OpenTelemetry (OTel)
2. Traces sent to Grafana Cloud (via Alloy or direct OTLP)
3. Span metrics generated from those traces (auto-configured in Grafana Cloud)

Docs: https://grafana.com/docs/grafana-cloud/monitor-applications/application-observability/

## Architecture

```
Your Application
    |
    | OTel SDK (OTLP gRPC/HTTP)
    v
Grafana Alloy (local collector)  OR  direct to Grafana Cloud
    |
    |-- Traces --> Grafana Tempo --> Span Metrics Generator
    |                                        |
    |                                        v
    |-- Metrics ----------------------> Grafana Mimir
    |
    |-- Logs ----> Grafana Loki
    |
    v
Application Observability UI (Service Inventory, Service Map, etc.)
```

## Step 1: Instrument Your Application with OTel

### Required Resource Attributes

These MUST be set for Application Observability to function correctly:

```bash
# Minimum required
OTEL_SERVICE_NAME=my-api

# Strongly recommended
OTEL_RESOURCE_ATTRIBUTES=service.namespace=my-team,deployment.environment=production,service.version=1.2.3
```

How Grafana uses these:
- `service.name` -> `service_name` label, used throughout UI
- `service.namespace` + `service.name` -> `job` label (`namespace/service.name`)
- `deployment.environment` -> `deployment_environment` label, used for environment filtering
- `service.version` -> shown in Service Overview; used for release comparison

Additional attributes for enriched UI:
```bash
OTEL_RESOURCE_ATTRIBUTES=\
  service.namespace=payments,\
  deployment.environment=production,\
  service.version=2.3.1,\
  k8s.cluster.name=prod-us-east,\
  k8s.namespace.name=payments-ns,\
  cloud.region=us-east-1,\
  host.name=payments-worker-1
```

### Node.js Example

```bash
npm install @opentelemetry/sdk-node \
            @opentelemetry/auto-instrumentations-node \
            @opentelemetry/exporter-trace-otlp-grpc
```

```javascript
// tracing.js - load BEFORE your app
const { NodeSDK } = require('@opentelemetry/sdk-node');
const { getNodeAutoInstrumentations } = require('@opentelemetry/auto-instrumentations-node');
const { OTLPTraceExporter } = require('@opentelemetry/exporter-trace-otlp-grpc');
const { Resource } = require('@opentelemetry/resources');
const { SEMRESATTRS_SERVICE_NAME, SEMRESATTRS_SERVICE_NAMESPACE } = require('@opentelemetry/semantic-conventions');

const sdk = new NodeSDK({
  resource: new Resource({
    [SEMRESATTRS_SERVICE_NAME]: 'my-node-api',
    [SEMRESATTRS_SERVICE_NAMESPACE]: 'my-team',
    'deployment.environment': 'production',
    'service.version': '1.2.0',
  }),
  traceExporter: new OTLPTraceExporter({
    url: 'http://localhost:4317', // Alloy or direct
  }),
  instrumentations: [getNodeAutoInstrumentations()],
});

sdk.start();
```

Run with:
```bash
node -r ./tracing.js app.js
```

### Python Example

```bash
pip install opentelemetry-distro opentelemetry-exporter-otlp
opentelemetry-bootstrap -a install
```

```python
# Manual setup (alternatively use opentelemetry-instrument CLI)
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk.resources import Resource

resource = Resource.create({
    "service.name": "my-python-api",
    "service.namespace": "my-team",
    "deployment.environment": "production",
    "service.version": "1.0.0",
})

provider = TracerProvider(resource=resource)
exporter = OTLPSpanExporter(endpoint="http://localhost:4317", insecure=True)
provider.add_span_processor(BatchSpanProcessor(exporter))
trace.set_tracer_provider(provider)
```

Or using the auto-instrumentation CLI:
```bash
OTEL_SERVICE_NAME=my-python-api \
OTEL_RESOURCE_ATTRIBUTES="service.namespace=my-team,deployment.environment=production" \
OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317 \
opentelemetry-instrument python app.py
```

### Java Example

Using the OTel Java agent (zero-code instrumentation):

```bash
wget https://github.com/open-telemetry/opentelemetry-java-instrumentation/releases/latest/download/opentelemetry-javaagent.jar

OTEL_SERVICE_NAME=my-java-api \
OTEL_RESOURCE_ATTRIBUTES="service.namespace=my-team,deployment.environment=production,service.version=1.0.0" \
OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317 \
java -javaagent:opentelemetry-javaagent.jar -jar myapp.jar
```

Grafana also provides a custom Java distribution:
```bash
# Grafana's distribution with extra features
wget https://github.com/grafana/grafana-opentelemetry-java/releases/latest/download/grafana-opentelemetry-java.jar
```

### Go Example

```bash
go get go.opentelemetry.io/otel \
       go.opentelemetry.io/otel/sdk \
       go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc
```

```go
package main

import (
    "go.opentelemetry.io/otel"
    "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc"
    "go.opentelemetry.io/otel/sdk/resource"
    sdktrace "go.opentelemetry.io/otel/sdk/trace"
    semconv "go.opentelemetry.io/otel/semconv/v1.21.0"
)

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

    exporter, _ := otlptracegrpc.New(ctx,
        otlptracegrpc.WithEndpoint("localhost:4317"),
        otlptracegrpc.WithInsecure(),
    )

    res, _ := resource.New(ctx,
        resource.WithAttributes(
            semconv.ServiceName("my-go-api"),
            semconv.ServiceNamespace("my-team"),
            semconv.ServiceVersion("1.0.0"),
            attribute.String("deployment.environment", "production"),
        ),
    )

    tp := sdktrace.NewTracerProvider(
        sdktrace.WithBatcher(exporter),
        sdktrace.WithResource(res),
    )
    otel.SetTracerProvider(tp)

    return func() { tp.Shutdown(ctx) }
}
```

## Step 2: Install and Configure Grafana Alloy

Alloy is the recommended local OTel collector that forwards data to Grafana Cloud.

### Install Alloy

```bash
# macOS
brew install grafana/grafana/alloy

# Linux (Debian/Ubuntu)
sudo apt-get install alloy

# Docker
docker run --rm \
  -v ./config.alloy:/etc/alloy/config.alloy \
  -p 4317:4317 -p 4318:4318 \
  grafana/alloy:latest run /etc/alloy/config.alloy

# Kubernetes (via Helm)
helm repo add grafana https://grafana.github.io/helm-charts
helm install alloy grafana/alloy \
  --set-file alloy.configMap.content=config.alloy
```

### Basic Alloy Config (config.alloy)

```river
// =========================================================
// OTLP Receiver - accepts data from instrumented apps
// =========================================================
otelcol.receiver.otlp "default" {
  grpc {
    endpoint = "0.0.0.0:4317"
  }
  http {
    endpoint = "0.0.0.0:4318"
  }
  output {
    metrics = [otelcol.processor.resourcedetection.default.input]
    logs    = [otelcol.processor.resourcedetection.default.input]
    traces  = [otelcol.processor.resourcedetection.default.input]
  }
}

// =========================================================
// Resource Detection - auto-adds cloud/host metadata
// =========================================================
otelcol.processor.resourcedetection "default" {
  // Detect from: env vars, system info, cloud providers
  detectors = ["env", "system", "gcp", "ec2", "azure"]

  system {
    hostname_sources = ["os"]
  }

  output {
    metrics = [otelcol.processor.transform.drop_unneeded.input]
    logs    = [otelcol.processor.transform.drop_unneeded.input]
    traces  = [otelcol.processor.transform.drop_unneeded.input]
  }
}

// =========================================================
// Transform - remove noisy/expensive attributes
// =========================================================
otelcol.processor.transform "drop_unneeded" {
  error_mode = "ignore"

  trace_statements {
    context    = "resource"
    statements = [
      // Remove high-cardinality attributes that increase storage cost
      // "delete_key(attributes, \"process.command_args\")",
    ]
  }

  output {
    metrics = [otelcol.processor.batch.default.input]
    logs    = [otelcol.processor.batch.default.input]
    traces  = [otelcol.processor.batch.default.input]
  }
}

// =========================================================
// Batch Processor - groups signals for efficient export
// =========================================================
otelcol.processor.batch "default" {
  send_batch_size    = 8192
  send_batch_max_size = 0
  timeout            = "200ms"

  output {
    metrics = [otelcol.exporter.otlphttp.grafana_cloud.input]
    logs    = [otelcol.exporter.otlphttp.grafana_cloud.input]
    traces  = [otelcol.exporter.otlphttp.grafana_cloud.input]
  }
}

// =========================================================
// Authentication
// =========================================================
otelcol.auth.basic "grafana_cloud" {
  username = env("GRAFANA_CLOUD_INSTANCE_ID")
  password = env("GRAFANA_CLOUD_API_KEY")
}

// =========================================================
// Export to Grafana Cloud
// =========================================================
otelcol.exporter.otlphttp "grafana_cloud" {
  client {
    endpoint = env("GRAFANA_CLOUD_OTLP_ENDPOINT")
    auth     = otelcol.auth.basic.grafana_cloud.handler
  }
}
```

### Environment Variables for Alloy

```bash
# From Grafana Cloud > My Account > Stack > OpenTelemetry
GRAFANA_CLOUD_OTLP_ENDPOINT=https://otlp-gateway-prod-us-east-0.grafana.net/otlp
GRAFANA_CLOUD_INSTANCE_ID=123456
GRAFANA_CLOUD_API_KEY=glc_eyJ...
```

## Step 3: Direct OTLP to Grafana Cloud (without Alloy)

If you prefer sending directly from your application:

```bash
# In your app's environment
OTEL_EXPORTER_OTLP_ENDPOINT=https://otlp-gateway-<region>.grafana.net/otlp
OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
# Header value: Basic base64("instanceID:apiKey")
OTEL_EXPORTER_OTLP_HEADERS=Authorization=Basic <base64-instanceid:apikey>
OTEL_SERVICE_NAME=my-api
OTEL_RESOURCE_ATTRIBUTES=service.namespace=myteam,deployment.environment=production
```

Get the base64 value:
```bash
echo -n "123456:glc_eyJ..." | base64
```

## Step 4: Span Metrics (How RED Metrics Are Generated)

Application Observability generates RED metrics from traces. This happens in two places:

### Option A: Tempo Metrics-Generator (Grafana Cloud default)

Grafana Cloud Tempo automatically runs the metrics-generator. No configuration needed for basic usage.

Generated metrics:
- `traces_spanmetrics_calls_total` - request rate (labeled by `span_name`, `status_code`, `service_name`)
- `traces_spanmetrics_duration_seconds` - latency histogram
- `traces_service_graph_request_total` - for service map
- `traces_service_graph_request_failed_total` - error count for service map

Span metric dimensions include by default:
- `service.name`
- `service.namespace`
- `deployment.environment`
- `service.version`
- `k8s.cluster.name`
- `cloud.region`

### Option B: OTel Collector Spanmetrics Connector

If using your own OTel Collector:

```yaml
# otelcol-config.yaml
receivers:
  otlp:
    protocols:
      grpc:
        endpoint: 0.0.0.0:4317
      http:
        endpoint: 0.0.0.0:4318

connectors:
  spanmetrics:
    histogram:
      explicit:
        buckets: [1ms, 5ms, 10ms, 25ms, 50ms, 100ms, 250ms, 500ms, 1s, 5s]
    dimensions:
      - name: service.namespace
      - name: deployment.environment
      - name: service.version
      - name: http.method
      - name: http.status_code
    exemplars:
      enabled: true
    namespace: "traces.span"

exporters:
  otlphttp/grafana:
    endpoint: "${GRAFANA_CLOUD_OTLP_ENDPOINT}"
    auth:
      authenticator: basicauth/grafana

  prometheusremotewrite/grafana:
    endpoint: "${GRAFANA_CLOUD_PROMETHEUS_ENDPOINT}"
    auth:
      authenticator: basicauth/grafana

extensions:
  basicauth/grafana:
    client_auth:
      username: "${GRAFANA_CLOUD_INSTANCE_ID}"
      password: "${GRAFANA_CLOUD_API_KEY}"

service:
  extensions: [basicauth/grafana]
  pipelines:
    traces:
      receivers: [otlp]
      exporters: [otlphttp/grafana, spanmetrics]
    metrics/spanmetrics:
      receivers: [spanmetrics]
      exporters: [prometheusremotewrite/grafana]
```

## Span Attributes for Best Results

App Observability uses specific span attributes to populate UI panels:

### HTTP Spans
```
http.method          GET, POST, etc.
http.status_code     200, 404, 500, etc.
http.route           /api/users/{id}
http.url             Full URL (use sparingly - high cardinality)
http.target          /api/users/123
http.scheme          http, https
```

### RPC Spans (gRPC)
```
rpc.system           grpc
rpc.service          mypackage.MyService
rpc.method           GetUser
rpc.grpc.status_code 0 (OK), 2 (UNKNOWN), 13 (INTERNAL), etc.
```

### Database Spans
```
db.system            postgresql, mysql, redis, mongodb
db.name              database name
db.operation         SELECT, INSERT, UPDATE
db.statement         SQL statement (careful with PII)
```

### Messaging Spans
```
messaging.system     kafka, rabbitmq, sqs
messaging.destination topic or queue name
messaging.operation  publish, receive, process
```

## Service Inventory and Service Map

### Service Inventory

Shows all services as a table with columns:
- Service name
- Rate (requests/sec)
- Error rate (%)
- Duration (p95 latency)
- Environment
- Technology badge (auto-detected from `telemetry.sdk.language`)

Filters available:
- Environment (`deployment.environment`)
- Namespace (`service.namespace`)
- Technology

### Service Map

Uses Tempo's `service-graphs` metrics generator:

Nodes = services (sized by request rate)
Edges = calls between services (direction determined by `span.kind`):
- `SPAN_KIND_CLIENT` = outgoing call (source node)
- `SPAN_KIND_SERVER` = incoming call (destination node)

For service map edges to form correctly, your spans need:
- Server spans: `span.kind = SERVER` with `server.address` or `peer.service`
- Client spans: `span.kind = CLIENT` targeting another service

Manual `peer.service` annotation (when automatic detection fails):
```python
with tracer.start_as_current_span("call-payment-service") as span:
    span.set_attribute("peer.service", "payment-api")
    span.set_attribute("span.kind", "CLIENT")
    # ... make the call
```

## Service Overview Page

Each service has a dedicated overview showing:

- **Rate** panel: requests/sec over time (from `traces_spanmetrics_calls_total`)
- **Errors** panel: error rate % (from status code != OK)
- **Duration** panel: p50, p95, p99 latency histograms
- **Operations** panel: top endpoints with individual RED metrics
- **Logs** panel: correlated logs (requires matching `service.name`)
- **Infrastructure** panel: pod/node metrics (requires K8s monitoring)
- **Profiles** button: link to Pyroscope (requires profiling setup)

## Configuring Baselines and Anomaly Detection

App Observability can show baseline metrics (ML-based) for anomaly highlighting:

Requirements:
- `deployment.environment` attribute must be set
- Minimum 2 weeks of data for baseline training
- Enable in Grafana Cloud > Application Observability > Settings

## Alert Rules for APM

Pre-built alert rules available in App Observability:
- High error rate (> threshold % of requests)
- High latency (p95 > SLO)
- Low request rate (sudden drops = potential outage)

Create custom PromQL alerts against span metrics:

```promql
# Error rate > 5% for any service
(
  sum by (service_name) (rate(traces_spanmetrics_calls_total{status_code="STATUS_CODE_ERROR"}[5m]))
  /
  sum by (service_name) (rate(traces_spanmetrics_calls_total[5m]))
) > 0.05

# p95 latency > 500ms
histogram_quantile(0.95,
  sum by (le, service_name) (
    rate(traces_spanmetrics_duration_seconds_bucket[5m])
  )
) > 0.5
```

## SLO Configuration

App Observability integrates with Grafana Cloud SLOs:

1. Navigate to Service Overview
2. Click "Create SLO" button
3. Select metric type: Availability (error rate) or Latency
4. Set target (e.g., 99.9% availability) and window (e.g., 28 days)
5. SLO dashboard auto-generates with error budget burn rate alerts

## Sampling Considerations

IMPORTANT: Generate span metrics BEFORE sampling. App Observability requires complete, unsampled trace data for accurate RED metrics.

Recommended pipeline with tail sampling:
```
App -> Alloy (receive all traces) -> Span Metrics (computed here) -> Tail Sampler -> Export samples to Tempo
                                          |
                                          v
                                   Grafana Mimir (all RED metrics, not just sampled)
```

In Alloy config:
```river
// Generate metrics from ALL traces before sampling
otelcol.connector.spanmetrics "default" {
  // dimensions...
  output {
    metrics = [otelcol.exporter.otlphttp.grafana_cloud.input]
  }
}

// Then apply tail sampling for trace storage cost control
otelcol.processor.tail_sampling "default" {
  decision_wait = "10s"
  policies = [
    { name = "errors", type = "status_code", status_code = { status_codes = ["ERROR"] } },
    { name = "slow",   type = "latency",     latency     = { threshold_ms = 500 } },
    { name = "sample", type = "probabilistic", probabilistic = { sampling_percentage = 10 } },
  ]
  output {
    traces = [otelcol.exporter.otlphttp.grafana_cloud.input]
  }
}
```

## Kubernetes Deployment

### Alloy as DaemonSet (recommended)

Running Alloy on every node enables host-level resource detection:

```yaml
# alloy-daemonset.yaml
apiVersion: apps/v1
kind: DaemonSet
metadata:
  name: alloy
  namespace: monitoring
spec:
  selector:
    matchLabels:
      app: alloy
  template:
    metadata:
      labels:
        app: alloy
    spec:
      containers:
        - name: alloy
          image: grafana/alloy:latest
          args:
            - run
            - /etc/alloy/config.alloy
          ports:
            - containerPort: 4317  # OTLP gRPC
              hostPort: 4317
            - containerPort: 4318  # OTLP HTTP
              hostPort: 4318
          env:
            - name: GRAFANA_CLOUD_OTLP_ENDPOINT
              valueFrom:
                secretKeyRef:
                  name: grafana-cloud-creds
                  key: otlp-endpoint
            - name: GRAFANA_CLOUD_INSTANCE_ID
              valueFrom:
                secretKeyRef:
                  name: grafana-cloud-creds
                  key: instance-id
            - name: GRAFANA_CLOUD_API_KEY
              valueFrom:
                secretKeyRef:
                  name: grafana-cloud-creds
                  key: api-key
          volumeMounts:
            - name: alloy-config
              mountPath: /etc/alloy
      volumes:
        - name: alloy-config
          configMap:
            name: alloy-config
```

### Application Pod Configuration

Point pods to the node-local Alloy instance:

```yaml
env:
  - name: OTEL_EXPORTER_OTLP_ENDPOINT
    value: "http://$(HOST_IP):4317"
  - name: HOST_IP
    valueFrom:
      fieldRef:
        fieldPath: status.hostIP
  - name: OTEL_SERVICE_NAME
    value: "my-api"
  - name: OTEL_RESOURCE_ATTRIBUTES
    value: "service.namespace=my-team,deployment.environment=production,k8s.pod.name=$(POD_NAME),k8s.namespace.name=$(NAMESPACE)"
  - name: POD_NAME
    valueFrom:
      fieldRef:
        fieldPath: metadata.name
  - name: NAMESPACE
    valueFrom:
      fieldRef:
        fieldPath: metadata.namespace
```

## Traces to Logs Correlation

For App Observability to show correlated logs in the Service Overview:

1. Inject trace context into log output
2. Use structured logging with `traceId` and `spanId` fields
3. Ensure logs have `service.name` label matching the OTel `service.name`

Example (Node.js with pino):
```javascript
const { trace } = require('@opentelemetry/api');

// In your logging middleware/utility:
function getTraceContext() {
  const span = trace.getActiveSpan();
  if (!span) return {};
  const { traceId, spanId } = span.spanContext();
  return { traceId, spanId };
}

logger.info({ ...getTraceContext(), userId: '123' }, 'User logged in');
// Output: {"traceId":"abc123","spanId":"def456","userId":"123","msg":"User logged in"}
```

Alloy can then extract these fields for Loki:
```river
loki.process "extract_trace" {
  stage.json {
    expressions = {
      traceId = "traceId",
      spanId  = "spanId",
    }
  }
  stage.labels {
    values = {
      traceId = "",
      spanId  = "",
    }
  }
  forward_to = [loki.write.grafana_cloud.receiver]
}
```

## Troubleshooting

### Service Not Appearing in Inventory

Check:
1. `service.name` resource attribute is set - this is mandatory
2. Traces are actually arriving in Tempo (check Explore > Tempo)
3. Span metrics are being generated (check Explore > Mimir, query `traces_spanmetrics_calls_total`)
4. `deployment.environment` is set (required for some views)

### Service Map Has Missing Connections

Check:
1. `span.kind` is set on spans (CLIENT for outgoing, SERVER for incoming)
2. `peer.service` is set on client spans (Alloy/Tempo uses this to create edges)
3. Service-graphs metrics generator is enabled (it is in Grafana Cloud by default)

### RED Metrics Show Wrong Values

Check:
1. Span metrics use `deployment.environment` (dotted) as source - not sanitized `deployment_environment`
2. Sampling is happening AFTER span metrics generation (not before)
3. Clock skew between services is not too large (affects histogram accuracy)

### Log Correlation Not Working

Check:
1. Log labels in Loki include `service_name` matching the OTel `service.name`
2. Loki data source is configured in Grafana
3. App Observability data source settings point to correct Loki instance

## Key Metric Names Reference

| Metric | Source | Description |
|---|---|---|
| `traces_spanmetrics_calls_total` | Tempo | Request count by service/operation |
| `traces_spanmetrics_duration_seconds` | Tempo | Latency histogram |
| `traces_spanmetrics_duration_seconds_bucket` | Tempo | Latency histogram buckets |
| `traces_service_graph_request_total` | Tempo | Service-to-service calls |
| `traces_service_graph_request_failed_total` | Tempo | Failed service-to-service calls |
| `traces_service_graph_request_server_seconds` | Tempo | Server-side latency for service graph |
| `traces_span_metrics_calls_total` | OTel Collector | Same as above (different source) |
| `traces_span_metrics_duration_seconds` | OTel Collector | Same as above (different source) |

Common labels on span metrics:
- `service_name` - from `service.name` attribute
- `span_name` - operation name (e.g., `GET /api/users`)
- `span_kind` - SERVER, CLIENT, etc.
- `status_code` - `STATUS_CODE_OK`, `STATUS_CODE_ERROR`, `STATUS_CODE_UNSET`
- `deployment_environment` - from `deployment.environment`

## References

- Application Observability: https://grafana.com/docs/grafana-cloud/monitor-applications/application-observability/
- Setup guide: https://grafana.com/docs/grafana-cloud/monitor-applications/application-observability/setup/
- Resource attributes: https://grafana.com/docs/grafana-cloud/monitor-applications/application-observability/setup/resource-attributes/
- Metrics and labels: https://grafana.com/docs/grafana-cloud/monitor-applications/application-observability/setup/metrics-labels/
- Alloy for OTel: https://grafana.com/docs/opentelemetry/collector/grafana-alloy/
- OTel semantic conventions: https://opentelemetry.io/docs/specs/semconv/
- Span metrics processor: https://grafana.com/docs/tempo/latest/metrics-from-traces/span-metrics/
apm.md 3.2 KB
# Application Observability (APM)

## What you get

- **Service Inventory** — RED metrics for every service
- **Service Overview** — per-service RED + top operations + error breakdown
- **Service Map** — node graph of dependencies (`span.kind=CLIENT/SERVER` for direction)
- **Operations view** — per-endpoint p50 / p95 / p99 latency

## How metrics are generated

Metrics come from **spanmetrics** (NOT from Prometheus scrape):

- Source: OTel traces sent to Tempo or Alloy
- Generator: Tempo metrics-generator (Cloud default) OR the `spanmetrics` connector in Alloy / OTel Collector
- Stored in Mimir

Key metric names:

| Source | Metric |
|--------|--------|
| Tempo metrics-generator | `traces_spanmetrics_calls_total`, `traces_spanmetrics_duration_seconds` |
| OTel Collector connector | `traces_span_metrics_calls_total`, `traces_span_metrics_duration_seconds` |
| Service Graph | `traces_service_graph_request_total`, `traces_service_graph_request_failed_total` |

## Required OTel resource attributes

| Attribute | Grafana label | Purpose |
|---|---|---|
| `service.name` | `service_name` / part of `job` | service identifier |
| `service.namespace` | part of `job` | groups services; `job = namespace/service.name` |
| `deployment.environment` | `deployment_environment` | env filter |

Recommended: `service.version`, `k8s.cluster.name`, `k8s.namespace.name`, `cloud.region`.

## OTel SDK env vars

```bash
export OTEL_SERVICE_NAME="my-api"
export OTEL_RESOURCE_ATTRIBUTES="service.namespace=myteam,deployment.environment=production,service.version=1.2.3"
export OTEL_EXPORTER_OTLP_ENDPOINT="http://localhost:4317"
export OTEL_EXPORTER_OTLP_PROTOCOL="grpc"
```

## Alloy config (River)

```alloy
otelcol.receiver.otlp "default" {
  grpc { endpoint = "0.0.0.0:4317" }
  http { endpoint = "0.0.0.0:4318" }
  output {
    metrics = [otelcol.processor.resourcedetection.default.input]
    logs    = [otelcol.processor.resourcedetection.default.input]
    traces  = [otelcol.processor.resourcedetection.default.input]
  }
}

otelcol.processor.resourcedetection "default" {
  detectors = ["env", "system", "gcp", "aws", "azure"]
  output {
    metrics = [otelcol.processor.batch.default.input]
    logs    = [otelcol.processor.batch.default.input]
    traces  = [otelcol.processor.batch.default.input]
  }
}

otelcol.processor.batch "default" {
  output {
    metrics = [otelcol.exporter.otlphttp.grafana_cloud.input]
    logs    = [otelcol.exporter.otlphttp.grafana_cloud.input]
    traces  = [otelcol.exporter.otlphttp.grafana_cloud.input]
  }
}

otelcol.auth.basic "grafana_cloud" {
  username = env("GRAFANA_CLOUD_INSTANCE_ID")
  password = env("GRAFANA_CLOUD_API_KEY")
}

otelcol.exporter.otlphttp "grafana_cloud" {
  client {
    endpoint = env("GRAFANA_CLOUD_OTLP_ENDPOINT")
    auth     = otelcol.auth.basic.grafana_cloud.handler
  }
}
```

Required env:

```bash
GRAFANA_CLOUD_OTLP_ENDPOINT=https://otlp-gateway-<region>.grafana.net/otlp
GRAFANA_CLOUD_INSTANCE_ID=<your-instance-id>
GRAFANA_CLOUD_API_KEY=<your-api-key>
```

## Correlation links (built-in)

- Metric spike → exemplar trace in Tempo
- Service Overview → Logs panel (joined by `service.name`)
- Service Overview → "Go to profiles" when Pyroscope configured
- App Observability ↔ Frontend Observability for same service
faro.md 3.2 KB
# Frontend Observability (Faro)

## SDK packages

```
@grafana/faro-core          # core API + transports
@grafana/faro-web-sdk       # web instrumentations + transports
@grafana/faro-web-tracing   # OpenTelemetry-JS distributed tracing
@grafana/faro-react         # React error boundary + router integration
```

## Basic web setup (npm)

```bash
npm install @grafana/faro-web-sdk
```

```javascript
import { initializeFaro, getWebInstrumentations } from '@grafana/faro-web-sdk';

const faro = initializeFaro({
  url: 'https://faro-collector-prod-<region>.grafana.net/collect/<app-key>',
  app: { name: 'my-frontend-app', version: '1.0.0', environment: 'production' },
  instrumentations: [
    ...getWebInstrumentations({ captureConsole: true }),
  ],
});

faro.api.pushLog(['User clicked checkout']);
faro.api.pushError(new Error('Payment failed'));
faro.api.pushEvent('button_click', { button: 'checkout' });
```

## CDN setup

```html
<script src="https://unpkg.com/@grafana/faro-web-sdk@latest/dist/library/faro-web-sdk.iife.js"></script>
<script>
  const { initializeFaro, getWebInstrumentations } = GrafanaFaroWebSdk;
  initializeFaro({
    url: 'https://faro-collector-prod-<region>.grafana.net/collect/<app-key>',
    app: { name: 'my-app', version: '1.0.0' },
    instrumentations: [...getWebInstrumentations()],
  });
</script>
```

## React + tracing

```bash
npm install @grafana/faro-react @grafana/faro-web-tracing
```

```javascript
import { initializeFaro, getWebInstrumentations } from '@grafana/faro-web-sdk';
import { TracingInstrumentation }               from '@grafana/faro-web-tracing';
import { createReactRouterV6DataOptions, ReactIntegration,
         withFaroRouterInstrumentation }        from '@grafana/faro-react';
import { createBrowserRouter, RouterProvider }  from 'react-router-dom';

initializeFaro({
  url: 'https://faro-collector-prod-<region>.grafana.net/collect/<app-key>',
  app: { name: 'my-react-app', version: '1.0.0', environment: 'production' },
  instrumentations: [
    ...getWebInstrumentations({ captureConsole: true }),
    new TracingInstrumentation(),
    new ReactIntegration({ router: createReactRouterV6DataOptions({}) }),
  ],
});

const router = withFaroRouterInstrumentation(createBrowserRouter([
  { path: '/',      element: <Home />  },
  { path: '/about', element: <About /> },
]));
```

## Session config

```javascript
initializeFaro({
  url: '...', app: { name: 'my-app' },
  sessionTracking: {
    enabled: true,
    persistent: true,
    maxSessionPersistenceTime: 4 * 60 * 60 * 1000, // 4 hours
    samplingRate: 1,  // 1 = 100%
    onSessionChange: (oldS, newS) => console.log('session', newS.id),
  },
  instrumentations: [...getWebInstrumentations()],
});
```

## Where to find the collector URL

Grafana Cloud → **Connections** → search "Frontend Observability" → click → **Web SDK Configuration** tab → copy the `url`.

## Auto-captured signals

- Page views + navigation timing
- Core Web Vitals (LCP, CLS, INP — INP replaces FID in Faro v2)
- JS errors + unhandled rejections
- Console errors / warnings (when `captureConsole: true`)
- Resource loading performance
- User interactions (clicks, form events)
- Fetch / XHR timing
- With `TracingInstrumentation`: `traceparent` header injection → backend trace correlation
frontend-observability.md 14.7 KB
# Grafana Frontend Observability - Faro SDK Reference

## What is Faro?

Grafana Faro is an open-source JavaScript/TypeScript SDK for Real User Monitoring (RUM). It instruments browser frontend applications to capture observability signals and correlate them with backend telemetry.

GitHub: https://github.com/grafana/faro-web-sdk
Docs: https://grafana.com/docs/grafana-cloud/monitor-applications/frontend-observability/

## Package Structure

| Package | Purpose |
|---|---|
| `@grafana/faro-core` | Core SDK foundation: signals, transports, API surface |
| `@grafana/faro-web-sdk` | Web instrumentations, web vitals, fetch/XHR, transports |
| `@grafana/faro-web-tracing` | OpenTelemetry-JS distributed tracing for browsers |
| `@grafana/faro-react` | React error boundary, router integration, component profiler |

## Installation

### NPM / Yarn

```bash
# Core SDK only
npm install @grafana/faro-web-sdk

# With distributed tracing
npm install @grafana/faro-web-sdk @grafana/faro-web-tracing

# With React integration
npm install @grafana/faro-web-sdk @grafana/faro-web-tracing @grafana/faro-react
```

### CDN (no bundler)

The library is distributed as IIFE and exposes a global `GrafanaFaroWebSdk`:

```html
<!-- Web SDK -->
<script src="https://unpkg.com/@grafana/faro-web-sdk@latest/dist/library/faro-web-sdk.iife.js"></script>

<!-- Web Tracing (optional) -->
<script src="https://unpkg.com/@grafana/faro-web-tracing@latest/dist/library/faro-web-tracing.iife.js"></script>

<script>
  const { initializeFaro, getWebInstrumentations } = GrafanaFaroWebSdk;
  const { TracingInstrumentation } = GrafanaFaroWebTracing;

  initializeFaro({
    url: 'https://faro-collector-prod-<region>.grafana.net/collect/<app-key>',
    app: { name: 'my-app', version: '1.0.0' },
    instrumentations: [
      ...getWebInstrumentations(),
      new TracingInstrumentation(),
    ],
  });
</script>
```

## Core Configuration - `initializeFaro()`

```typescript
interface FaroConfig {
  // Required: Collector endpoint URL from Grafana Cloud Frontend Observability
  url: string;

  // Application metadata
  app: {
    name: string;           // Required - identifies your app
    version?: string;       // Recommended - for release tracking
    environment?: string;   // e.g. 'production', 'staging'
    namespace?: string;     // Optional grouping
  };

  // Instrumentations to enable
  instrumentations?: Instrumentation[];

  // Session tracking options
  sessionTracking?: {
    enabled?: boolean;                  // default: true
    persistent?: boolean;               // survives tab close; default: false
    maxSessionPersistenceTime?: number; // ms; default: 4 hours
    samplingRate?: number;              // 0-1; default: 1 (100%)
    generateSessionId?: () => string;   // custom ID generator
    onSessionChange?: (oldSession: Session | null, newSession: Session) => void;
  };

  // Optional: override or add metadata
  user?: {
    id?: string;
    username?: string;
    email?: string;
    attributes?: Record<string, string>;
  };

  // Optional: global attributes added to all signals
  globalObjectKey?: string; // window key; default: '__faroBridge'

  // Batch send options
  batchSendCount?: number;   // signals per batch; default: 50
  batchSendTimeout?: number; // ms before forced flush; default: 250
}
```

## Minimal Setup

```javascript
import { initializeFaro, getWebInstrumentations } from '@grafana/faro-web-sdk';

initializeFaro({
  url: 'https://faro-collector-prod-us-east-0.grafana.net/collect/abc123',
  app: {
    name: 'my-app',
    version: '1.0.0',
    environment: 'production',
  },
  instrumentations: [...getWebInstrumentations()],
});
```

## `getWebInstrumentations()` Options

```javascript
getWebInstrumentations({
  // Capture console.log, console.warn, console.error as Faro logs
  captureConsole: true,           // default: false
  captureConsoleDisabledLevels: ['log'], // exclude certain levels

  // Capture page visibility changes
  capturePageVisibility: true,    // default: true
})
```

What's automatically included in `getWebInstrumentations()`:
- `PerformanceInstrumentation` - navigation timing, resource loading, web vitals
- `ErrorsInstrumentation` - unhandled errors and promise rejections
- `ConsoleInstrumentation` - console capture (if `captureConsole: true`)
- `SessionInstrumentation` - session lifecycle tracking
- `ViewInstrumentation` - page view tracking

## Web Vitals Captured

Faro v2 uses Web Vitals v5:
- **LCP** (Largest Contentful Paint) - loading performance
- **CLS** (Cumulative Layout Shift) - visual stability
- **INP** (Interaction to Next Paint) - interactivity (replaces FID)
- **FCP** (First Contentful Paint)
- **TTFB** (Time to First Byte)

## Manual API Usage

```javascript
const faro = initializeFaro({ ... });

// Push a log message
faro.api.pushLog(['User completed checkout'], {
  level: LogLevel.INFO,
  context: { orderId: '12345' },
});

// Push an error manually
faro.api.pushError(new Error('Payment gateway timeout'), {
  type: 'NetworkError',
  context: { endpoint: '/api/pay' },
});

// Push a custom event
faro.api.pushEvent('feature_used', {
  feature: 'dark_mode',
  source: 'settings_page',
});

// Push a measurement (custom metric)
faro.api.pushMeasurement({
  type: 'custom_timing',
  values: {
    checkout_duration_ms: 1234,
  },
});

// Set user context
faro.api.setUser({
  id: 'user-456',
  username: 'jane.doe',
  attributes: { plan: 'premium' },
});

// Set custom global attributes
faro.api.setSession({ attributes: { experiment: 'checkout-v2' } });
```

## Distributed Tracing Setup

Adds OpenTelemetry browser tracing to correlate frontend spans with backend traces.

```javascript
import { initializeFaro, getWebInstrumentations } from '@grafana/faro-web-sdk';
import { TracingInstrumentation } from '@grafana/faro-web-tracing';

initializeFaro({
  url: '...',
  app: { name: 'my-app' },
  instrumentations: [
    ...getWebInstrumentations(),
    new TracingInstrumentation({
      // Propagate trace context to these URLs (supports regex)
      propagateTraceHeaderCorsUrls: [
        /https:\/\/api\.myapp\.com\/.*/,
        'https://internal.service.com',
      ],
      // Custom sampling rate for traces (0-1)
      // samplingRate: 0.5,
    }),
  ],
});
```

When enabled:
- `traceparent` and `tracestate` headers are injected into all matching fetch/XHR requests
- Browser creates spans for each HTTP call
- Traces appear in Grafana Tempo correlated to backend spans
- Session ID is propagated as a baggage item

## React Integration

### React Router v6 (data router API - recommended)

```javascript
import { initializeFaro, getWebInstrumentations } from '@grafana/faro-web-sdk';
import { TracingInstrumentation } from '@grafana/faro-web-tracing';
import {
  createReactRouterV6DataOptions,
  ReactIntegration,
  withFaroRouterInstrumentation,
} from '@grafana/faro-react';
import { createBrowserRouter, RouterProvider } from 'react-router-dom';

// Must call BEFORE rendering
initializeFaro({
  url: 'https://faro-collector-prod-<region>.grafana.net/collect/<key>',
  app: { name: 'my-react-app', version: '2.0.0', environment: 'production' },
  instrumentations: [
    ...getWebInstrumentations({ captureConsole: true }),
    new TracingInstrumentation(),
    new ReactIntegration({
      router: createReactRouterV6DataOptions({}),
    }),
  ],
});

// Instrument the router
const router = withFaroRouterInstrumentation(
  createBrowserRouter([
    { path: '/', element: <HomePage /> },
    { path: '/products/:id', element: <ProductPage /> },
    { path: '/checkout', element: <CheckoutPage /> },
  ])
);

function App() {
  return <RouterProvider router={router} />;
}
```

### React Router v6 (non-data router - Routes component)

```javascript
import {
  createReactRouterV6Options,
  ReactIntegration,
  FaroRoutes,
} from '@grafana/faro-react';
import { useLocation, useNavigationType, createRoutesFromChildren, matchRoutes } from 'react-router-dom';

initializeFaro({
  // ...
  instrumentations: [
    ...getWebInstrumentations(),
    new TracingInstrumentation(),
    new ReactIntegration({
      router: createReactRouterV6Options({
        useLocation,
        useNavigationType,
        createRoutesFromChildren,
        matchRoutes,
      }),
    }),
  ],
});

// In your component tree, use FaroRoutes instead of Routes:
function AppRoutes() {
  return (
    <FaroRoutes>
      <Route path="/" element={<HomePage />} />
      <Route path="/about" element={<AboutPage />} />
    </FaroRoutes>
  );
}
```

### React Router v4/v5

```javascript
import {
  createReactRouterV5Options,
  ReactIntegration,
} from '@grafana/faro-react';
import { createBrowserHistory } from 'history';
import { Router } from 'react-router-dom';

const history = createBrowserHistory();

initializeFaro({
  // ...
  instrumentations: [
    ...getWebInstrumentations(),
    new TracingInstrumentation(),
    new ReactIntegration({
      router: createReactRouterV5Options({ history }),
    }),
  ],
});

// Wrap app with Router using the same history instance
function App() {
  return (
    <Router history={history}>
      <YourRoutes />
    </Router>
  );
}
```

### React Error Boundary

```javascript
import { FaroErrorBoundary, withErrorBoundary } from '@grafana/faro-react';

// As a component
function App() {
  return (
    <FaroErrorBoundary
      fallback={<ErrorFallback />}
      pushErrorAsFaro={true}       // auto-pushes to Faro (default: true)
    >
      <MainContent />
    </FaroErrorBoundary>
  );
}

// As a HOC
const SafeComponent = withErrorBoundary(MyComponent, {
  fallback: <p>Something went wrong</p>,
});
```

## Session Tracking Details

```javascript
import {
  initializeFaro,
  getWebInstrumentations,
  SessionInstrumentation,
} from '@grafana/faro-web-sdk';

initializeFaro({
  url: '...',
  app: { name: 'my-app' },
  sessionTracking: {
    enabled: true,

    // Persist session across browser restarts (uses localStorage)
    persistent: true,

    // Max time a persistent session lives (milliseconds)
    // Default: 4 hours
    maxSessionPersistenceTime: 4 * 60 * 60 * 1000,

    // Sample only 50% of sessions to reduce data volume
    samplingRate: 0.5,

    // Custom session ID (useful for server-side session correlation)
    generateSessionId: () => crypto.randomUUID(),

    // Hook for analytics or logging on session rotation
    onSessionChange: (oldSession, newSession) => {
      console.log(`New session: ${newSession.id}`);
      analytics.track('session_started', { id: newSession.id });
    },
  },
  instrumentations: [...getWebInstrumentations()],
});
```

## Session Replay

Session Replay records DOM mutations using rrweb, allowing visual playback of user sessions.

Setup steps:
1. In Grafana Cloud > Connections > Frontend Observability > Web SDK Configuration
2. Enable "Session Replay" toggle to get a replay-enabled collector URL
3. Install the SDK - the collector key controls what's recorded server-side

The basic `initializeFaro` setup works - session replay is controlled by the collector URL/key:

```javascript
initializeFaro({
  // Use the replay-enabled collector URL from Grafana Cloud UI
  url: 'https://faro-collector-prod-<region>.grafana.net/collect/<replay-enabled-key>',
  app: { name: 'my-app', version: '1.0.0' },
  instrumentations: [...getWebInstrumentations()],
  sessionTracking: {
    persistent: true,
    samplingRate: 0.1, // Record 10% of sessions for replay (cost control)
  },
});
```

In Grafana Cloud Frontend Observability:
- Sessions panel shows timeline of user actions
- "Play" button on any session opens the replay viewer
- Filters: by error, by duration, by user, by URL

## Getting Collector URL

The collector URL is unique per application and environment:

1. Navigate to Grafana Cloud stack
2. Left menu: **Connections** > search "Frontend Observability"
3. Click the Frontend Observability tile
4. Click **Web SDK Configuration** tab
5. Copy the `url` field shown (format: `https://faro-collector-prod-<region>.grafana.net/collect/<app-key>`)

The same page shows:
- Your App Name (pre-configured)
- Sample rate settings
- Replay toggle
- CDN script tags for quick integration

## Fetch Instrumentation Customization

Control which requests are traced and what headers are captured:

```javascript
import { FetchInstrumentation } from '@grafana/faro-web-sdk';

initializeFaro({
  // ...
  instrumentations: [
    new FetchInstrumentation({
      // Capture specific request headers
      requestHeaders: ['x-request-id', 'x-correlation-id'],
      // Capture specific response headers
      responseHeaders: ['x-trace-id'],
      // Ignore certain URLs from tracking
      ignoredUrls: [/.*\/health/, 'https://analytics.internal/'],
    }),
  ],
});
```

## Data Flow Architecture

```
Browser App
    |
    | (HTTP POST, batched)
    v
Faro Collector (Grafana Cloud)
    |
    |-- Logs -------> Grafana Loki
    |-- Traces -----> Grafana Tempo
    |-- Metrics ----> Grafana Mimir
    |
Visualized in Grafana Cloud Frontend Observability dashboards
```

Alternative with self-hosted Alloy:
```
Browser App --> Grafana Alloy (faro.receiver) --> Grafana Cloud backends
```

## Alloy Configuration (self-hosted)

If routing through your own Alloy instance:

```river
faro.receiver "default" {
  server {
    listen_address           = "0.0.0.0"
    listen_port              = 12347
    cors_allowed_origins     = ["https://myapp.com"]
    api_key                  = env("FARO_API_KEY")
    max_allowed_payload_size = "10MiB"
  }

  sourcemaps {
    download          = true
    upload {
      external_url = "https://myfrontend.cdn.com"
    }
  }

  output {
    logs   = [loki.write.grafana_cloud.receiver]
    traces = [otelcol.exporter.otlphttp.grafana_cloud.input]
  }
}
```

## Correlation with Backend

Frontend-to-backend trace correlation requires:

1. Faro has `TracingInstrumentation` enabled
2. Backend accepts W3C `traceparent` headers
3. Both frontend and backend send to the same Grafana Cloud Tempo instance

In Tempo trace view, the root span will show `session.id` attribute linking to the Faro session.

In Frontend Observability, errors show "View trace" button when a `traceId` is present.

## Upgrading to Faro v2

Faro v2 changes from v1:
- **Web Vitals v5**: FID removed, INP added as Core Web Vital
- **Console instrumentation**: Simplified - `captureConsole` is now an option in `getWebInstrumentations()`
- **Tracing APIs**: Some deprecated span attributes removed
- **Session attributes**: New structured approach

Migration: https://grafana.com/docs/grafana-cloud/monitor-applications/frontend-observability/instrument/upgrading/upgrade-v2/

## Prebuilt Dashboards in Grafana Cloud

Frontend Observability auto-provisions:
- **Overview** - session count, error rate, web vitals scores
- **Sessions** - session list with replay links
- **Errors** - error grouping, stack traces, affected sessions
- **Performance** - web vitals trends, resource loading, navigation timing
- **User Journey** - page flow, drop-off points

License (Apache-2.0)

View full license text
Licensed under the Apache License, Version 2.0. See https://github.com/grafana/skills/blob/main/LICENSE