
Claude Code agent observability with Docker Compose and Amazon Managed Grafana: Build an agent cost and token dashboard
Track Claude Code agent cost and tokens with OpenTelemetry, Docker Compose and Amazon Managed Grafana. Local dashboard first, then a team view on AWS.
AI Engineering
AI coding agents consume tokens in ways that are difficult to see. A single request in Claude Code can start a subagent, and that subagent can call several tools, each of which sends more context back to the model. The developer reads the final answer. The invoice shows a monthly total. Neither one explains which agent or which model produced the cost.
Claude Code can export this information as OpenTelemetry metrics and log events. Metrics answer the live question: what is the agent spending right now on this machine? Log events answer the historical question: how did the cost and the tool behavior of many developers change over the last two weeks? The two questions suit two different tools.
This article builds a viewer for both, in four steps. You enable telemetry, run an OpenTelemetry Collector with Prometheus and Grafana in Docker Compose, chart the metrics locally, and then send the same data to AWS. Metrics go to Amazon Managed Service for Prometheus. Log events go to Amazon CloudWatch Logs. Amazon Managed Grafana reads both and shows the team view.

Figure 1. Where Claude Code telemetry travels.
A note on scope. The Compose file, collector configurations, Grafana provisioning files, IAM policy and dashboard JSON were checked for syntax and structure only. They were not run against a live AWS account while this draft was written. The dashboard images use illustrative data. Prometheus metric names and Logs Insights field names are the most likely to need adjustment, so each step ends with a check.
You end up with a local Grafana dashboard, an Amazon Managed Service for Prometheus workspace, a CloudWatch log group named
claude-code-events , a nine-panel Amazon Managed Grafana team dashboard, and a teardown for all of it.What you need
- An AWS account where you can create a Prometheus workspace, a log group, an IAM policy and a Grafana workspace.
- AWS IAM Identity Center enabled. The Grafana workspace signs users in through it.
- AWS CLI v2, signed in, and Docker with Docker Compose v2.24 or later.
- Claude Code installed, and a Region where both managed services are available (the examples use
us-east-1).
git clone https://github.com/jubins/claude-code-aws-observability.gitcd claude-code-aws-observabilityArchitecture and design decisions
Two signals, two stores. Metrics are counters with a small set of attributes, such as model, query source and token type, which suits a time series database. Log events carry one record per request, with a session identifier and exact token counts. Stored as metrics, they would create a new time series for every session, so Logs Insights filters and ranks them instead.
Keep the local stack. Prometheus and Grafana in Compose cost nothing and update in seconds. They let you confirm the data before AWS bills anything, and they keep working when credentials expire.
Managed services over servers. Amazon Managed Service for Prometheus and Amazon Managed Grafana remove servers a team would otherwise patch and secure. The tradeoff is paying per sample and per active user.
Temporary credentials on a laptop, a role in production. The collector signs requests with credentials from the standard AWS chain. On a laptop, a script exports short-lived credentials. A shared collector should run on ECS or EC2 with an IAM role.
The console for the Grafana workspace. Per the CreateWorkspace API reference, service-managed permissions are supported only in the console. The CLI and CloudFormation require customer-managed permissions, so this article uses the console for that one step.
What Claude Code emits
Claude Code exports telemetry through the standard OpenTelemetry environment variables. The documentation lists eight metrics. The following table shows the ones that this article uses.
Metric | What it counts | Attributes used here |
|---|---|---|
claude_code.cost.usage | Cost of the session in USD | model , query_source , agent.name |
claude_code.token.usage | Tokens used | type (input, output, cacheRead, cacheCreation), model |
claude_code.session.count | Sessions started | start_type |
claude_code.code_edit_tool.decision | Accept or reject decisions on edits | decision , tool_name |
The log events carry more detail, because Claude Code writes one event for each occurrence instead of a running total. Two events matter for cost and reliability. The
claude_code.api_request event describes one request to the model, with the attributes model , cost_usd , duration_ms , input_tokens , output_tokens , cache_read_tokens , cache_creation_tokens and query_source . The claude_code.tool_result event describes one tool call, with tool_name , success and duration_ms . The success attribute is the text "true" or "false".The attribute
query_source turns a cost report into an agent report. It identifies the part of the system that issued a request. The main conversation and each subagent have different values, and background work has its own value, so the cost of delegation becomes visible. The values shown in the illustrations ( main , subagent , auxiliary ) are examples. Step 6 includes a query that lists the real values in your data.

Figure 2. One agent run, two kinds of telemetry.
Prompt text is a separate matter. Claude Code redacts prompts, assistant responses and tool parameters by default, and each has its own opt-in variable. This article leaves all of them disabled, so no prompt content reaches CloudWatch Logs.
Step 1: Enable telemetry
Telemetry is off until
CLAUDE_CODE_ENABLE_TELEMETRY is set to 1 . The following file sets the exporters, the protocol and the endpoint that the collector will expose. A shell that sources it starts every later Claude Code session with telemetry enabled.# Source this file in the shell that starts Claude Code: source claude-telemetry.envexport CLAUDE_CODE_ENABLE_TELEMETRY=1export OTEL_METRICS_EXPORTER=otlpexport OTEL_LOGS_EXPORTER=otlpexport OTEL_EXPORTER_OTLP_PROTOCOL=grpcexport OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317export OTEL_METRIC_EXPORT_INTERVAL=10000export OTEL_LOGS_EXPORT_INTERVAL=5000
# Keep session.id off the metrics: it creates a new time series per session.export OTEL_METRICS_INCLUDE_SESSION_ID=falseClaude Code has no default protocol, so the file sets
OTEL_EXPORTER_OTLP_PROTOCOL explicitly. The short metric interval of ten seconds is useful during setup. A longer interval means fewer samples later.The file also sets
OTEL_METRICS_INCLUDE_SESSION_ID to false ; the documented default is true . A session identifier on every metric grows local storage and drives the sample count that Amazon Managed Service for Prometheus bills. Session-level detail stays available in the log events.Step 2: Run the collector, Prometheus and Grafana locally
The Compose file starts three containers. The collector receives OTLP from Claude Code. Prometheus scrapes the metrics that the collector exposes. Grafana reads Prometheus and loads a dashboard from provisioning files. All published ports are bound to
127.0.0.1 , so only your machine can reach them. That matters because Grafana runs with anonymous admin access.# Requires Docker Compose v2.24 or later (optional env_file entries).services: otel-collector: image: ${OTELCOL_IMAGE:-otel/opentelemetry-collector-contrib:latest} command: ["--config=/etc/otelcol/config.yaml"] environment: AWS_REGION: ${AWS_REGION:-us-east-1} AMP_REMOTE_WRITE_URL: ${AMP_REMOTE_WRITE_URL:-} LOG_STREAM_NAME: ${LOG_STREAM_NAME:-dev-laptop} # Written by scripts/refresh-aws-creds.sh. Absent in the local-only stage. env_file: - path: .env.aws required: false volumes: - ./${COLLECTOR_CONFIG:-otel-collector-local.yaml}:/etc/otelcol/config.yaml:ro ports: - 127.0.0.1:4317:4317 - 127.0.0.1:4318:4318
prometheus: image: prom/prometheus:latest command: ["--config.file=/etc/prometheus/prometheus.yml"] volumes: - ./prometheus.yml:/etc/prometheus/prometheus.yml:ro - prometheus-data:/prometheus ports: - 127.0.0.1:9090:9090 depends_on: - otel-collector
grafana: image: grafana/grafana-oss:latest environment: GF_AUTH_ANONYMOUS_ENABLED: "true" GF_AUTH_ANONYMOUS_ORG_ROLE: Admin volumes: - ./grafana/provisioning:/etc/grafana/provisioning:ro - ./grafana/dashboards:/var/lib/grafana/dashboards:ro - grafana-data:/var/lib/grafana ports: - 127.0.0.1:3000:3000 depends_on: - prometheus
volumes: prometheus-data: grafana-data:The first-stage collector config (
otel-collector-local.yaml ) has the same OTLP receiver and the same deltatocumulative and batch processors as the full AWS file in Step 5. Its metrics pipeline exports only to a prometheus exporter on port 8889. Its logs pipeline exports to the debug exporter, so log events print to the collector log before AWS is involved.The
deltatocumulative processor converts delta metrics to cumulative ones by keeping a running total in memory. It is there because the Prometheus exporter serves cumulative values, and the documentation does not state which temporality Claude Code uses by default. Its stability level is alpha, so check the current README.Prometheus needs only one scrape job, which targets
otel-collector:8889 every 15 seconds.Start the stack from the folder, enable telemetry in your shell and run Claude Code.
cp .env.example .envdocker compose up -dsource claude-telemetry.envclaude

Figure 3. The Compose stack in Docker Desktop.
Verify. Send one prompt in Claude Code, wait about 30 seconds, and then check that the metrics arrived.
docker compose pscurl -s 'http://localhost:9090/api/v1/label/__name__/values' | grep -o 'claude_code_[a-zA-Z_]*'docker compose logs otel-collector --tail 20The second command should list metric names that start with
claude_code_ . Write down the exact names. Step 3 and Step 6 use them in queries. The third command should show log event records from the debug exporter.Step 3: Chart agent cost and tokens locally
Grafana reads its configuration from files, so the dashboard exists as soon as the container starts. Two small provisioning files in the repository (
grafana/provisioning/datasources/prometheus.yaml and grafana/provisioning/dashboards/claude-code.yaml ) point it at http://prometheus:9090 and at the dashboard folder.The dashboard file
grafana/dashboards/claude-code-agents.json holds eight panels. Each one is a short PromQL expression.Panel | PromQL |
|---|---|
Cost in range | sum(increase(claude_code_cost_usage_USD_total[$__range])) |
Tokens in range | sum(increase(claude_code_token_usage_tokens_total[$__range])) |
Sessions in range | sum(increase(claude_code_session_count_total[$__range])) |
Edit accept rate | sum(increase(claude_code_code_edit_tool_decision_total{decision="accept"}[$__range])) / sum(increase(claude_code_code_edit_tool_decision_total[$__range])) |
Cost by model | sum by (model) (increase(claude_code_cost_usage_USD_total[$__rate_interval])) |
Cost by query source | sum by (query_source) (increase(claude_code_cost_usage_USD_total[$__rate_interval])) |
Tokens by type | sum by (type) (increase(claude_code_token_usage_tokens_total[$__rate_interval])) |
Cost by named agent | sum by (agent_name) (increase(claude_code_cost_usage_USD_total{agent_name!=""}[$__rate_interval])) |
Metric names change on the way into Prometheus. The exporter normalizes names and can append a unit suffix and a counter suffix, which is why a metric called
claude_code.cost.usage becomes claude_code_cost_usage_USD_total . Compare the names that you wrote down in Step 2 with the ones above. If they differ, edit the JSON file, and Grafana will pick up the change.

Figure 4. The local Grafana dashboard (panel set differs slightly from the shipped JSON).
Verify. Open
http://localhost:3000 , go to the Claude Code folder and open the dashboard. After a few prompts, the cost, token and session panels should show values, and the cost by query source panel should split the main conversation from any subagents. The last panel stays empty until Claude Code attaches an agent name to cost metrics.Step 4: Create the AWS side
This step creates a metrics workspace, grants the collector permission to write, and prepares credentials. The log group needs no setup, because the collector creates it.
A metrics workspace
export AWS_REGION=us-east-1export ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
export AMP_WORKSPACE_ID=$(aws amp create-workspace --alias claude-code --region $AWS_REGION --query workspaceId --output text)
aws amp describe-workspace --workspace-id $AMP_WORKSPACE_ID --region $AWS_REGION --query workspace.status.statusCode --output text
export AMP_REMOTE_WRITE_URL="https://aps-workspaces.${AWS_REGION}.amazonaws.com/workspaces/${AMP_WORKSPACE_ID}/api/v1/remote_write"echo $AMP_REMOTE_WRITE_URLRepeat the
describe-workspace command until it prints ACTIVE .A least-privilege policy
The collector needs to write metrics to one workspace and write events to one log group. Nothing else.
{ "Version": "2012-10-17", "Statement": [ { "Sid": "WriteMetricsToAmp", "Effect": "Allow", "Action": "aps:RemoteWrite", "Resource": "arn:aws:aps:__REGION__:__ACCOUNT_ID__:workspace/__AMP_WORKSPACE_ID__" }, { "Sid": "WriteEventsToCloudWatchLogs", "Effect": "Allow", "Action": [ "logs:CreateLogGroup", "logs:CreateLogStream", "logs:PutLogEvents", "logs:DescribeLogStreams", "logs:PutRetentionPolicy" ], "Resource": [ "arn:aws:logs:__REGION__:__ACCOUNT_ID__:log-group:claude-code-events", "arn:aws:logs:__REGION__:__ACCOUNT_ID__:log-group:claude-code-events:*" ] } ]}The first statement allows remote write to the workspace that you just created. The second statement covers the log group. The exporter calls
CreateLogGroup and PutRetentionPolicy the first time it runs, because the configuration sets a 30-day retention, so those two actions are included and limited to this one log group. Fill in the placeholders and create the policy.sed -e "s/__REGION__/$AWS_REGION/g" -e "s/__ACCOUNT_ID__/$ACCOUNT_ID/g" -e "s/__AMP_WORKSPACE_ID__/$AMP_WORKSPACE_ID/g" iam/collector-policy.json > iam/collector-policy.rendered.json
aws iam create-policy --policy-name ClaudeCodeTelemetryWriter --policy-document file://iam/collector-policy.rendered.jsonThen attach the policy to the identity that your AWS profile uses. With IAM Identity Center, add it to your permission set, or create a dedicated role that your profile assumes.
Credentials for the collector
The collector runs in a container, so it needs credentials that it can read from its environment. The script below exports temporary credentials from your profile into
.env.aws , which the Compose file loads, and then restarts the collector. The credentials expire when your session does, so run the script again when they do. The .gitignore in the folder excludes .env.aws .#!/usr/bin/env bash# Export temporary credentials for the collector and restart it. Re-run when they expire.set -euo pipefail
: "${AWS_PROFILE:?Set AWS_PROFILE to the profile that holds the collector policy}"
# SSO profiles need a fresh login first: aws sso login --profile "$AWS_PROFILE"aws configure export-credentials --profile "$AWS_PROFILE" --format env-no-export > .env.awschmod 600 .env.aws
docker compose up -d --force-recreate otel-collectorecho "Collector restarted with credentials from profile: $AWS_PROFILE"Now point Compose at the AWS configuration. Edit
.env :AWS_REGION=us-east-1COLLECTOR_CONFIG=otel-collector-aws.yamlAMP_REMOTE_WRITE_URL=<the value printed by the echo command above>LOG_STREAM_NAME=<your hostname>Step 5: Send metrics and log events to AWS
The AWS configuration keeps the local Prometheus exporter and adds two AWS exporters.
# Stage 2: local Prometheus plus AWS (SigV4 remote write and CloudWatch Logs).extensions: sigv4auth: region: ${env:AWS_REGION} service: aps
receivers: otlp: protocols: grpc: endpoint: 0.0.0.0:4317 http: endpoint: 0.0.0.0:4318
processors: deltatocumulative: {} batch: timeout: 5s # Flatten names and fix types for Logs Insights. transform/claude_logs: error_mode: ignore log_statements: - context: log statements: - set(attributes["event_name"], attributes["event.name"]) where attributes["event.name"] != nil - replace_pattern(attributes["event_name"], "^claude_code\\.", "") where attributes["event_name"] != nil - set(attributes["session_id"], attributes["session.id"]) where attributes["session.id"] != nil - set(attributes["cost_usd"], Double(attributes["cost_usd"])) where attributes["cost_usd"] != nil - set(attributes["duration_ms"], Double(attributes["duration_ms"])) where attributes["duration_ms"] != nil - set(attributes["input_tokens"], Int(attributes["input_tokens"])) where attributes["input_tokens"] != nil - set(attributes["output_tokens"], Int(attributes["output_tokens"])) where attributes["output_tokens"] != nil - set(attributes["cache_read_tokens"], Int(attributes["cache_read_tokens"])) where attributes["cache_read_tokens"] != nil - set(attributes["cache_creation_tokens"], Int(attributes["cache_creation_tokens"])) where attributes["cache_creation_tokens"] != nil
exporters: prometheus: endpoint: 0.0.0.0:8889 prometheusremotewrite/amp: endpoint: ${env:AMP_REMOTE_WRITE_URL} auth: authenticator: sigv4auth # Creates the log group and stream if missing. awscloudwatchlogs: region: ${env:AWS_REGION} log_group_name: claude-code-events log_stream_name: ${env:LOG_STREAM_NAME} log_retention: 30
service: extensions: [sigv4auth] pipelines: metrics: receivers: [otlp] processors: [deltatocumulative, batch] exporters: [prometheus, prometheusremotewrite/amp] logs: receivers: [otlp] processors: [transform/claude_logs, batch] exporters: [awscloudwatchlogs]-
sigv4authsigns the remote write requests for theapsservice in your Region, using credentials from the standard AWS chain. The Prometheus remote write exporter references it withauthenticator: sigv4auth, and theservice.extensionslist must include it.
-
prometheusremotewrite/ampreceives the same cumulative metrics as the local Prometheus exporter. The metrics pipeline lists both exporters, so the local dashboard keeps working if AWS is unreachable.
-
transform/claude_logsflattens dotted attribute names such asevent.nameandsession.idintoevent_nameandsession_id, and converts cost, duration and token counts to numbers. Without it, Logs Insights would need escaping for dotted names and might treat numeric strings as text.error_mode: ignoreskips a statement when its attribute is missing, which is normal because atool_resultevent has no cost.
-
awscloudwatchlogswrites each log event as a JSON record into theclaude-code-eventslog group, with 30-day retention. According to its README, the exporter wraps the log record in JSON unlessraw_logis set, so attributes should appear under anattributesobject. That shape is an inference, and Step 6 relies on it, so check it in the verification below.
Run the refresh script. It exports credentials and restarts the collector with the new configuration.
export AWS_PROFILE=<your-profile>aws sso login --profile $AWS_PROFILE # only for IAM Identity Center profiles./scripts/refresh-aws-creds.shVerify the events. Send a prompt in Claude Code, wait a minute, and read the log group.
docker compose logs otel-collector --tail 30aws logs tail claude-code-events --since 15m --region $AWS_REGIONThe collector log should show no 403 or
ExpiredToken errors. The log group should show JSON records. Confirm that each record has an attributes object that contains event_name , session_id and, for model requests, numeric cost_usd and token counts. If the names differ, adjust the queries in Step 6 to match.Verify the metrics. The
awscurl tool signs requests for you. The profile that you use here also needs the aps:GetLabels permission, which the writer policy does not grant.pip install awscurlawscurl --service aps --region $AWS_REGION --profile $AWS_PROFILE "https://aps-workspaces.${AWS_REGION}.amazonaws.com/workspaces/${AMP_WORKSPACE_ID}/api/v1/label/__name__/values" | grep -o 'claude_code_[a-zA-Z_]*'You should see the same metric names that the local Prometheus listed in Step 2.
Step 6: Build the team dashboard in Amazon Managed Grafana
Create the workspace
Use the console, for the reason given in the design decisions.
- Open the Amazon Managed Grafana console and choose Create workspace. Name it
claude-code-observability.
- For authentication, choose AWS IAM Identity Center.
- For permissions, choose Service managed and Current account.
- Under data sources, select Amazon Managed Service for Prometheus and Amazon CloudWatch. This lets the service create read access for them.
- Create the workspace, wait for it to become active, and assign yourself as an Admin. Assign your team as Viewers.
- Open the workspace URL and sign in through IAM Identity Center.
- In the workspace, find the AWS data sources page, add Amazon Managed Service for Prometheus for your Region and workspace, and add Amazon CloudWatch. Menu names change between Grafana versions, so look for that page rather than a fixed path.
Test the Logs Insights queries first
The log panels use four CloudWatch Logs Insights queries. Run each one in the CloudWatch console under Logs Insights, with the log group
claude-code-events and a time range that covers your test prompts. Start by looking at one raw record, so that you know the field names.fields @message| sort @timestamp desc| limit 5Tool failure rate. Because
success is the text "true" or "false", strcontains turns it into 1 or 0, and the average of those values is the failure rate. The failure rate panel uses the query below without the by clause.Tool reliability. Calls, failures and 95th percentile duration for each tool.
filter attributes.event_name = "tool_result"| fields strcontains(attributes.success, "false") as failed| stats count(*) as calls, sum(failed) as failures, pct(attributes.duration_ms, 95) as p95_ms by attributes.tool_name| sort calls desc| limit 20Most expensive sessions. The
session_id attribute is only in the log events, because Step 1 removed it from the metrics.filter attributes.event_name = "api_request"| fields strcontains(attributes.query_source, "subagent") as is_subagent| stats sum(attributes.cost_usd) as cost_usd, count(*) as requests, sum(is_subagent) as subagent_requests by attributes.session_id| sort cost_usd desc| limit 10Cache hit ratio per day. The share of input that the model read from its cache.
filter attributes.event_name = "api_request"| stats sum(attributes.cache_read_tokens) as cache_read, sum(attributes.cache_creation_tokens) as cache_creation, sum(attributes.input_tokens) as fresh_input by bin(1d)| fields bin(1d), cache_read / (cache_read + cache_creation + fresh_input) as cache_hit_ratioCheck three assumptions in the console: records expose attributes as
attributes.<name> , a fields command after stats can do arithmetic on the stats aliases, and the Grafana CloudWatch data source draws bin(1d) as a time series. If the second fails, drop the last line of the cache query and compute the ratio in a Grafana transformation.To list the real
query_source values in your data, run this and update the string subagent in the sessions query if your values differ:filter attributes.event_name = "api_request"| stats count(*) as requests, sum(attributes.cost_usd) as cost_usd by attributes.query_source| sort cost_usd descImport the dashboard
The dashboard file has placeholders for your Region and account. The script fills them in. Then, in Grafana, choose Dashboards, New, Import, and upload the rendered file.
./scripts/render-team-dashboard.sh# upload amg/claude-code-agents-team.rendered.json in the Grafana import pageThe dashboard has two data source variables at the top. Select your Amazon Managed Service for Prometheus data source in the first and your CloudWatch data source in the second. The nine panels are the three cost, token and session totals from Prometheus, the tool failure rate from Logs Insights, two cost charts from Prometheus, and the tool reliability, expensive sessions and cache hit ratio panels from Logs Insights.

Figure 5. The team dashboard in Amazon Managed Grafana
Verify. Every panel should show data after a few Claude Code sessions. The Prometheus panels depend on the metric names from Step 2, and the Logs Insights panels depend on the field names from Step 5. A panel that shows no data points to one of those two.
What the dashboards tell you about an agent
- Delegation. If subagents account for a large share of cost, review what each subagent loads into its context and whether the task needed delegation at all.
- Model choice. The cost by model panel shows how much work runs on the larger model, and where routine tasks could move to the cheaper one.
- Context. A low cache hit ratio means the model reads the same material at the full input price. The chart shows the day it began to fall.
- Tools. A tool with a high failure rate or a long 95th percentile makes the agent wait and retry. The reliability and expensive sessions tables show which tool and which sessions.
Where it is likely to break
What to check first:
Symptom | Likely cause | What to check |
|---|---|---|
Remote write returns 403 | The policy names a different workspace ID or Region, or the identity does not have the policy | The policy resource ARN, and aws sts get-caller-identity for the same profile |
ExpiredToken errors after some hours | The exported credentials expired | Run scripts/refresh-aws-creds.sh again |
The log group stays empty | The logs pipeline fails, or the policy lacks a CloudWatch Logs action | The collector log, the policy actions, and aws logs describe-log-groups |
Logs Insights returns no rows | Field names differ from attributes.event_name and similar | Run fields @message | limit 5 and compare |
Prometheus panels are empty in Amazon Managed Grafana, but local ones work | Metric names differ, or the wrong data source is selected | The two data source variables, and Explore with the label names query |
Production considerations
Security
- No long-lived keys. The collector uses temporary credentials on a laptop and an IAM role in a shared deployment.
- Least privilege. The policy allows one
aps:RemoteWriteresource and one log group. The Grafana workspace gets read access to the two data sources through its service-managed role.
- No prompt content. Prompts, responses and tool parameters stay redacted. Opting in would write them to CloudWatch Logs, where anyone with log access can read them.
Cost
This is a back-of-envelope estimate for 50 developers, not a measurement. Rates are US East (N. Virginia) list prices as I found them on 10 November 2026; the CloudWatch Logs figures come from third-party summaries. Confirm every rate on the AWS pricing pages before you budget.
Meter | Rate | Assumed volume | Per month |
|---|---|---|---|
Metric samples ingested | $0.90 per 10 million samples, first 2 billion | 43.2 million. 30 series, one sample every 10 s, 4 active hours a day, 20 days, 50 developers. An upper bound. | $3.89 |
Log ingestion | $0.50 per GB | 4 GB. 2,000 events a day at 2 KB for each developer, 20 days. | $2.00 |
Log storage | $0.03 per GB-month | 4 GB, uncompressed upper bound, 30-day retention | $0.12 |
Logs Insights scans | $0.005 per GB scanned | 4 log panels scan a 2 GB window on each load. 12 viewers, 5 loads a day, 22 days: 1,320 loads at $0.04. | $52.80 |
Amazon Managed Grafana | $9 per active editor, $5 per active viewer, per workspace | 2 editors and 10 viewers | $68.00 |
Total | | | about $127 |
Ingestion costs about $6 a month. The Grafana seats and the Logs Insights scans cost most. One dashboard load scans about 8 GB and costs $0.04, so a one-minute auto-refresh would cost about $19 a day. That is why the dashboard file ships with auto-refresh off. To lower scan cost, shorten the time range of the log panels, or compute the cache hit ratio from the token metric, which needs no log scan.
Reliability and cardinality
The remote write exporter buffers in memory, so a long AWS outage can lose samples while the local Prometheus keeps its copy. Every attribute value you add to a metric multiplies the series count, which is why Step 1 removed the session identifier. Pin the collector image version, because the CloudWatch Logs exporter is beta and
deltatocumulative is alpha.Roll it out to a team
Claude Code reads managed settings, which can set the same
CLAUDE_CODE_* and OTEL_* variables as Step 1 centrally, with the endpoint pointing at a shared collector. When managed settings define the endpoint, protocol or credentials, Claude Code removes conflicting developer values, so developers cannot redirect telemetry. Run the shared collector on Amazon ECS or EC2 with an IAM role, and add transport security and authentication before it accepts traffic from many machines.Clean up
These commands are destructive. Review them before you run them. Deleting the Grafana workspace removes its dashboards, and deleting the log group removes the events.
# Local stack (also unset the OTEL_* variables in your shell)docker compose down -vrm -f .env.aws iam/collector-policy.rendered.json amg/claude-code-agents-team.rendered.json
# AWS resourcesexport AMG_WORKSPACE_ID=$(aws grafana list-workspaces --region $AWS_REGION --query "workspaces[?name=='claude-code-observability'].id" --output text)aws grafana delete-workspace --workspace-id $AMG_WORKSPACE_ID --region $AWS_REGIONaws amp delete-workspace --workspace-id $AMP_WORKSPACE_ID --region $AWS_REGIONaws logs delete-log-group --log-group-name claude-code-events --region $AWS_REGION
# IAM policy: detach it from the role or permission set first, then delete itaws iam detach-role-policy --role-name <your-role> --policy-arn arn:aws:iam::$ACCOUNT_ID:policy/ClaudeCodeTelemetryWriteraws iam delete-policy --policy-arn arn:aws:iam::$ACCOUNT_ID:policy/ClaudeCodeTelemetryWriterThen confirm that nothing billable remains: leftover Grafana and Prometheus workspaces, the log group, IAM roles starting with
AmazonGrafanaServiceRole , CloudFormation stack sets created by service-managed permissions, and IAM Identity Center assignments. Finally, check the Billing dashboard.Where this leaves you
The local stack answers what an agent is spending during the current session. The AWS stack answers how agent use changed across a team over weeks. Both read telemetry that Claude Code produces without any change to the agent itself. The part to take away is the split: metrics for the live and aggregate questions, events for the questions that need a session or a tool, and a bill that you can predict because each signal goes where its volume is cheapest.
References
- Companion repository: https://github.com/jubins/claude-code-aws-observability
- Claude Code monitoring and usage (OpenTelemetry): https://code.claude.com/docs/en/monitoring-usage
- AWS CloudWatch Logs exporter (OpenTelemetry Collector Contrib): https://pkg.go.dev/github.com/open-telemetry/opentelemetry-collector-contrib/exporter/awscloudwatchlogsexporter
- Amazon Managed Service for Prometheus, ingest metrics with OpenTelemetry: https://docs.aws.amazon.com/prometheus/latest/userguide/AMP-onboard-ingest-metrics-OpenTelemetry.html
- Amazon Managed Grafana, CreateWorkspace API: https://docs.aws.amazon.com/grafana/latest/APIReference/API\_CreateWorkspace.html
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article