跳转到内容
Documentation

Cosmos DB Monitoring — Enable Azure Log Analytics for NoSqlStudio

A complete, hand-held walkthrough to wire Azure Log Analytics to your Cosmos DB for MongoDB account so NoSqlStudio's Cosmos Optimizer can light up every chart. Three paths: Portal (mm-by-mm), one-line CLI script, or Terraform.

Estimated time: ~25 minutes (Portal path) · ~5 minutes (CLI / Terraform)
In this manual

Introduction

This manual takes you from a Cosmos DB account that does not yet emit telemetry to one that streams every request into NoSqlStudio's Operations Center in under ten minutes. You don't need to know what a Service Principal, Log Analytics workspace, or Diagnostic Setting is beforehand — the 💡 boxes explain each concept the first time it appears.

What you get when this is done

  • Six live charts in the Operations Center: RU/s consumed, throttles (HTTP 429), p99 latency, error count, projected $/hour cost, and top-partition share.
  • An anomaly detector that flags cost spikes, throttle storms, latency excursions, and partition skew the moment they happen.
  • A Query Cost pane that shows you the actual RU charge of every command — with the raw mongosh text so you can Explain it and feed it to the built-in AI advisor.
  • Every recorded tick optionally mirrored to your own MongoDB management database, with a 30-day TTL, so history survives across machines and laptop restarts.

How to read this manual

Each step has:

  • Do — the exact action (click, type, run such-and-such command).
  • See — what should happen. This is your “pass / fail”.
  • Why — only when it helps you understand (skip if you're in a hurry).

Concept

Concept box. Explains a term right when it appears.

Heads-up

Heads-up. A subtle gotcha that tends to bite people.

Before you start

Concept

The four moving parts you'll create

1. Service Principal — a non-human identity in your Azure tenant; NoSqlStudio uses it to read Log Analytics without storing any human password. 2. Log Analytics workspace — Azure's centralised log lake; this is where Cosmos drops its telemetry. 3. Diagnostic Setting — the wire that pipes Cosmos logs into the workspace. Without it the workspace stays empty forever. 4. Role assignments — two of them, so the SP can read both the workspace and the metrics on the resource group.

You will need:

  1. 1An Azure subscription with Owner or Contributor rights on the resource group that holds the Cosmos account (you need to be able to create role assignments).
  2. 2Permission in Azure Active Directory to create a Service Principal — or, if your shop forbids that, the object ID of an existing SP your platform team set up for monitoring.
  3. 3Azure CLI (az) version 2.55 or later for paths B and C. Install: <https://learn.microsoft.com/cli/azure/install-azure-cli>
  4. 4(Path C only) Terraform ≥ 1.5.0.

Pick your path

All three paths produce the same six credentials you paste into NoSqlStudio. Pick whichever matches how you work:

  • Path A — Azure Portal. Click-by-click in the browser. Best for a one-off, or when you want to see what's being created. ~25 min the first time, ~10 min once familiar.
  • Path B — CLI script. Download a single .sh (Linux/macOS) or .ps1 (Windows) and run it. Best for a quick one-shot or when you don't have Terraform. ~5 min total.
  • Path C — Terraform. A reusable module. Best when you provision Cosmos via Terraform anyway, or when you operate multiple environments. ~5 min once init finishes.

Concept

All paths are idempotent: re-running them is safe. They detect existing resources and update / reuse instead of duplicating.

Stage 1

Collect the one input every path needs

Whichever path you pick, you'll need the resource ID of the Cosmos account you want to monitor. Get it once and keep it on a sticky note for the next 10 minutes.

Step 1

Find your Cosmos account's Resource ID

Do

Open the Azure Portal → search the top bar for the name of your Cosmos account → click the result → in the left sidebar click Properties → copy the long string under Resource ID.

See

You'll have a value shaped exactly like this:

text·1 linha
/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/my-rg/providers/Microsoft.DocumentDB/databaseAccounts/my-cosmos-acct

Concept

Reading the Resource ID

The four slash-separated chunks that matter are: • `/subscriptions/<sub-guid>` — your subscription ID (you'll need this later). • `/resourceGroups/<rg-name>` — where the account lives. The Log Analytics workspace will land here too. • `/databaseAccounts/<acct-name>` — the Cosmos account itself.

Why

Every path below — Portal, CLI, Terraform — starts with this string. Getting it right once saves three round-trips back to the Portal.

Heads-up

Don't confuse the Resource ID with the Log Analytics Workspace ID you'll see later. The first is a slash-path; the second is a bare GUID. NoSqlStudio asks for both in separate fields.

Stage 2

Path A — Azure Portal (click-by-click)

Skip to Stage 3 if you're going CLI, or Stage 4 if you're going Terraform. Stages 2, 3 and 4 are mutually exclusive — pick one.

Concept

What you're about to do

Six clicks-heavy steps: create an Azure AD app + SP (Steps 2-4), create the Log Analytics workspace with a daily cost cap (Step 5), grant the SP read access to it (Step 6), and wire the Cosmos account to the workspace (Step 7). Then you're done with Azure — Stage 5 is just pasting values into NoSqlStudio.

Step 2

Create the Azure AD App Registration

Concept

App Registration vs Service Principal

When you create an App Registration, Azure quietly creates a matching Service Principal in the background. The App Registration is the definition (name, allowed redirect URIs, secrets); the Service Principal is the instance that gets role assignments. You'll see both terms used interchangeably — they refer to the same identity.

Do

Top-bar search → App registrations → click New registration. Fill in:

  • Name: nosqlstudio-cosmos-monitoring (any name works, but be consistent across environments).
  • Supported account types: leave at Accounts in this organizational directory only.
  • Redirect URI: leave empty — NoSqlStudio uses the client-credentials OAuth flow, no browser redirect.
Do

Click Register.

See

You land on the new app's Overview page. Three values are visible there — write down Application (client) ID and Directory (tenant) ID; you'll paste them into NoSqlStudio at the end.

Why

The client ID identifies which app is calling Azure; the tenant ID identifies which Azure AD directory the app lives in. NoSqlStudio needs both to negotiate a token.

Step 3

Generate a client secret for the App

Do

Still on the App Registration, in the left sidebar → Certificates & secrets+ New client secret.

  • Description: anything memorable, e.g. nosqlstudio-prod-2026.
  • Expires: 24 months (best balance of security vs. how often you have to rotate). Azure caps the maximum at 24 months.
Do

Click Add. The secret appears with a Value column.

Heads-up

Copy the Value NOW. Once you navigate away you cannot retrieve it — Azure shows it exactly once. Paste it into a password manager. Don't confuse Value (the secret) with Secret ID (a useless identifier).

Why

Azure never shows secrets twice on purpose, so a leaked screenshot of the page can't be retroactively exploited. If you lose it, you have to create a new secret and update NoSqlStudio's Cloud Credentials.

Step 4

Grant the SP "Monitoring Reader" on the resource group

Concept

Why this scope, not subscription-wide?

Least privilege. The SP only needs to read metrics + diagnostic-setting state on the Cosmos account. Scoping to the resource group keeps the blast radius tight — even if the SP's secret leaks, the attacker can only enumerate / read monitoring metadata in that one resource group.

Do

Top-bar search → name of the resource group that holds your Cosmos account → click it → left sidebar → Access control (IAM)+ AddAdd role assignment.

  • Role tab: search for `Monitoring Reader` → select it → click Next.
  • Members tab: Assign access to = User, group, or service principal+ Select members → search for nosqlstudio-cosmos-monitoring (the name from Step 2) → click it → click Select.
  • Review + assignReview + assign.
See

A green pill at the top: Role assignment added. Within ~30 seconds the new assignment appears under the Role assignments tab of the IAM page.

Step 5

Create the Log Analytics workspace (with a cost cap)

Do

Top-bar search → Log Analytics workspaces+ Create. Fill in:

  • Subscription + Resource group: same as the Cosmos account.
  • Name: nosqlstudio-monitoring.
  • Region: the same region as your Cosmos account (minimises ingestion latency + zero cross-region egress fees).
Do

Click Review + CreateCreate. After ~30 seconds you land on the new workspace.

Do

Now set a cost cap so a future runaway log doesn't bankrupt anyone. In the workspace's sidebar → SettingsUsage and estimated costsDaily capOn → enter `1` in the GB field → OK.

Concept

Reading the cost cap

The workspace stops ingesting new logs once it has received 1 GB in a single UTC day. Already-ingested data keeps flowing through queries. The cap resets at midnight UTC. 1 GB/day is enough for ~30 million `MongoRequests` rows at the typical row size — generous for most accounts.

See

On the same page, Data retention defaults to 30 days. Leave it there — 30 days is the free floor; bumping it above 30 starts costing extra per GB-month.

Do

Click Overview in the sidebar and copy the Workspace ID GUID at the top of the page. Stash it next to the values from Step 2.

Heads-up

Workspace ID ≠ Resource ID. The Workspace ID is a bare GUID like 3e1bee3d-7752-4606-9c95-208626ef0406. The Resource ID is a slash-path. NoSqlStudio asks for the GUID.

Step 6

Grant the SP "Log Analytics Reader" on the workspace

Do

Still on the workspace → left sidebar → Access control (IAM)+ AddAdd role assignment.

  • Role: search for `Log Analytics Reader` → select → Next.
  • Members: + Select members → search `nosqlstudio-cosmos-monitoring` → select → Select.
  • Review + assignReview + assign.
Why

Step 4's Monitoring Reader covers metrics + diagnostic-setting metadata on the resource group, but not running KQL queries against the workspace itself. That's a separate role, on a separate scope.

Step 7

Route Cosmos logs to the workspace (Diagnostic Setting)

Heads-up

This is the step everyone forgets

The Cosmos account does not automatically send anything to your workspace just because the workspace exists in the same RG. You have to explicitly route the logs. Without this step the workspace stays empty and NoSqlStudio shows “MongoRequests table is empty” forever.

Do

Navigate back to your Cosmos DB account → left sidebar → Monitoring section → Diagnostic settings+ Add diagnostic setting.

  • Diagnostic setting name: nosqlstudio-monitoring.
  • Under Logs, tick MongoRequests only. Leave the others unticked unless you've read the cost guardrails in Stage 6 — PartitionKeyRUConsumption and QueryRuntimeStatistics produce 5-10× more ingestion volume.
  • Under Destination details: tick Send to Log Analytics workspace → select your subscription → select nosqlstudio-monitoring (the workspace from Step 5).
  • Under the Destination table picker, choose Resource specific, NOT Azure diagnostics.

Concept

Resource-specific vs Azure-diagnostics tables

Resource-specific routes Cosmos logs into the CDBMongoRequests table — a typed, denormalised schema that's both cheaper to query and easier on the bill. Azure-diagnostics dumps everything into one huge AzureDiagnostics table with JSON-blob columns. NoSqlStudio's KQL queries are written against the Resource-specific table — pick it.

Do

Click Save.

See

A green pill: Successfully created diagnostic setting. The new setting now appears in the list.

Why

Once saved, the Cosmos engine begins shipping every request to the workspace in near real-time. There's a 2-5 minute ingestion lag between when a request hits the engine and when it's queryable in Log Analytics — that's normal and isn't a bug.

Step 8

Find your Subscription ID and Tenant ID

Do

Top-bar search → Subscriptions → click your subscription. The Subscription ID is the GUID at the top of the Overview page. Copy it.

Do

Top-bar search → Microsoft Entra ID (formerly Azure Active Directory) → the Tenant ID GUID is on the Overview page. Copy it.

Concept

If you wrote down the Tenant ID back in Step 2, you can skip the second part of this step — it's the same value.

Stage 3

Path B — One-line CLI script

If you'd rather skip the Portal entirely, a single script does all of Stage 2 in one shot. Skip to Stage 5 once you've run it.

Concept

What the script does

It's an idempotent wrapper around az CLI invocations. It logs you in (az login), creates the SP, the workspace (with the 1 GB daily cap), and the Diagnostic Setting; assigns both roles; and prints the six credentials you paste into NoSqlStudio. Re-running it rotates the client secret instead of duplicating resources.

Step 9

Install the Azure CLI

Do

If you don't already have az installed, follow Microsoft's installer for your OS:

  • Windows: download the MSI from <https://aka.ms/installazurecliwindows>
  • macOS: brew install azure-cli
  • Debian / Ubuntu: curl -sL https://aka.ms/InstallAzureCLIDeb | sudo bash
  • RHEL / Fedora: sudo dnf install azure-cli (after adding the Microsoft repo)
Do

Confirm with:

bash·1 linha
az version
See

You should see something like:

Console output
{
  "azure-cli": "2.66.0",
  ...
}

Heads-up

The script requires az ≥ 2.55. Older versions are missing flags it uses.

Step 10

Download the script

Do

Choose your shell:

  • Bash (Linux / macOS / WSL): curl -O https://nosqlstudio.com/scripts/setup-cosmos-monitoring.sh && chmod +x setup-cosmos-monitoring.sh
  • PowerShell (Windows): Invoke-WebRequest -OutFile setup-cosmos-monitoring.ps1 -Uri https://nosqlstudio.com/scripts/setup-cosmos-monitoring.ps1

Concept

Open the file in any editor — it's a clean, commented shell script with no telemetry, no remote calls, and no hidden state. Read it before you run it; that's exactly the point of distributing the source.

Step 11

Run it

Do

Paste your Cosmos Resource ID (Step 1) and run:

bash·3 linhas
# Bash
./setup-cosmos-monitoring.sh \
  --cosmos-resource-id "/subscriptions/.../databaseAccounts/my-cosmos-acct"
powershell·3 linhas
# PowerShell
.\setup-cosmos-monitoring.ps1 `
  -CosmosResourceId "/subscriptions/.../databaseAccounts/my-cosmos-acct"
See

If you're not logged in, a browser window opens for az login. After that the script prints progress:

Console output
▸ Preflight
▸ Checking Azure CLI login
✓ Logged into subscription 00000000-... (tenant ...)
▸ Verifying Cosmos account my-cosmos-acct exists
✓ Cosmos account reachable
▸ Looking up Service Principal 'nosqlstudio-cosmos-monitoring'
▸ Creating Service Principal 'nosqlstudio-cosmos-monitoring'
✓ Service Principal created (appId abc..., secret valid 2 years)
▸ Sleeping 20s for Azure AD propagation
▸ Locating / creating Log Analytics workspace 'nosqlstudio-monitoring' in 'my-rg'
▸ Creating workspace (region eastus2, retention 30d, cap 1 GB/day)
✓ Workspace created
▸ Granting 'Log Analytics Reader' to SP on the workspace
✓ Granted
▸ Configuring Diagnostic Setting 'nosqlstudio-monitoring' on Cosmos account
✓ Diagnostic Setting configured (Resource-specific tables)
▸ Verifying configuration
✓ Verified

  SUCCESS    Paste the values below into NoSqlStudio:
  ...
Why

Each line prefixed is an action; each is success. If anything fails the script bails immediately with a red line and a non-zero exit — fix the cause and re-run; the steps already completed will be detected and skipped.

Step 12

Optional flags

Useful overrides when defaults don't suit:

bash·7 linhas
./setup-cosmos-monitoring.sh \
  --cosmos-resource-id "$RID" \
  --workspace-name      nosqlstudio-prod   \
  --workspace-region    westeurope         \
  --workspace-daily-cap-gb 5                \
  --include-partition-key-ru                \
  --verbose
  • --workspace-daily-cap-gb 5 — raise the 1 GB/day cap when you have very heavy traffic. Costs scale linearly.
  • --include-partition-key-ru / --include-query-runtime-stats — add extra log categories. Significantly more ingestion volume; only enable if you specifically need them.
  • --existing-sp-app-id <appId> — reuse an SP your platform team already has; the script skips Step 2/3.
  • --verbose — print every az call's response.
Stage 4

Path C — Terraform module

For shops that drive Azure via Terraform. The published module wraps everything Stage 2 / 3 do, with full output plumbing so you can wire the six credentials into a downstream secret manager (Key Vault, Vault, etc.).

Step 13

Minimal example

Do

Create a folder cosmos-monitoring/, put this in main.tf, then terraform init && terraform apply:

hcl·19 linhas
terraform {
  required_version = ">= 1.5.0"
}

provider "azurerm" {
  features {}
}
provider "azuread" {}

module "cosmos_monitoring" {
  source = "github.com/nosqlstudio/nosqlstudio-site//terraform/cosmos-monitoring?ref=main"

  cosmos_account_resource_id = "/subscriptions/.../databaseAccounts/my-cosmos-acct"
  region                     = "eastus2"
  log_analytics_daily_quota_gb = 1
}

output "nosqlstudio_credentials"   { value = module.cosmos_monitoring.nosqlstudio_credentials }
output "nosqlstudio_client_secret" { value = module.cosmos_monitoring.nosqlstudio_client_secret, sensitive = true }
See

After apply:

bash·11 linhas
terraform output nosqlstudio_credentials
# {
#   "clientId"               = "..."
#   "logAnalyticsWorkspaceId" = "3e1bee3d-..."
#   "resourceId"             = "/subscriptions/..."
#   "subscriptionId"         = "00000000-..."
#   "tenantId"               = "..."
# }

terraform output -raw nosqlstudio_client_secret
# <the 6th value>
Step 14

Common variations

  • BYO Service Principal: set create_service_principal = false + pass existing_service_principal_object_id = "<obj-id>". The module still creates the workspace + Diagnostic Setting and grants the BYO SP both roles. You need to provide the client secret out-of-band.
  • Budget alert: set create_budget_alert = true + budget_monthly_usd = 25 + budget_alert_email = "you@example.com" for a subscription-scoped monthly budget that emails at 80% actual and 100% forecast.
  • Multiple log categories: diagnostic_log_categories = ["MongoRequests", "PartitionKeyRUConsumption"].

Concept

Full variable reference

Every variable + every output is documented in the module's README.md. From the source folder, open terraform/cosmos-monitoring/README.md — or grab it from the published repo.

Stage 5

Paste the six credentials into NoSqlStudio

Same final step regardless of which path you took. Whatever you wrote down or whatever Terraform / the script printed: paste it now.

Step 15

Open Cosmos Optimizer

Do

In NoSqlStudio, open the Cosmos DB connection you want to monitor. From the menu: ToolsCosmos Optimizer (or press Ctrl + Alt + Shift + O).

See

A new workspace tab opens with a sidebar listing 11 panes grouped under Diagnostics, Cost & Capacity, Operations, Configuration.

Step 16

Open the Cloud Credentials pane

Do

In the Cosmos Optimizer sidebar, scroll to the Configuration group → click Cloud Credentials.

See

A form with six fields (plus a label header for each) — paste the values you collected:

  • Subscription ID — the GUID from Step 8 (or printed by the script / Terraform).
  • Tenant ID — the Directory (tenant) ID from Step 2.
  • Client ID — the Application (client) ID from Step 2.
  • Client Secret — the secret Value from Step 3 (the one Azure showed once).
  • Resource ID — the full Cosmos resource ID from Step 1.
  • Log Analytics Workspace ID — the GUID from Step 5 (NOT the resource ID).
Do

Click Save.

See

A green pill appears: Saved. The status dot next to the gear icon in the Operations Center toolbar (top-right) should turn green within a few seconds.

Step 17

Verify in the Operations Center

Do

Click Operations Center (top of the sidebar, under Diagnostics). Wait up to 2 minutes for the first poll cycle.

See

Three things should happen, in this order:

  1. 1The amber banner No telemetry captured yet disappears.
  2. 2The six small charts (RU/s, Throttles, Latency p99, Errors, Cost, Top partition share) begin filling left-to-right.
  3. 3Click the gear ⚙ in the toolbar — the modal says Connected — recorded snapshots are being mirrored (assuming you've also configured the management database; that's a separate one-time toggle).

Concept

If charts stay empty for more than 5 minutes

Most likely the Cosmos account isn't receiving any traffic right now. Open a connection to it in NoSqlStudio and run any query (e.g. db.runCommand({ping:1}) in the Mongo shell) — within 2-5 minutes the chart should jump.

Heads-up

If charts still stay empty after 10 minutes with traffic flowing, jump to Stage 6 — Troubleshooting.

Stage 6

Cost guardrails + troubleshooting

Step 18

Cost expectations

With the defaults (only MongoRequests, 1 GB/day cap, 30-day retention):

  • Light traffic Cosmos account (<10 req/s): ~US$ 0.50 / month, almost entirely Log Analytics ingestion at the PerGB2018 rate.
  • Moderate (10-100 req/s): ~US$ 2-3 / month — typical small SaaS shop.
  • Heavy (> 100 req/s): hits the 1 GB/day cap; the workspace stops ingesting until midnight UTC. Charts go quiet. By design — protects against runaway cost.

Concept

If your account is heavy and you want full coverage: raise the daily cap incrementally (1 → 5 → 10 GB) and watch the first month's bill. Don't jump straight to no-cap — set the cap higher rather than disabling it.

If you've enabled the optional categories (Stage 2 Step 7) — PartitionKeyRUConsumption or QueryRuntimeStatistics — expect 5-10× more ingestion volume. Plan for US$ 10-40 / month at typical traffic.

Step 19

Charts went empty 50 minutes ago and won't come back

Two common causes:

  1. 1Daily cap was hit. Open the workspace → Usage and estimated costs → look for the red Daily cap exceeded banner at the top. Either raise the cap or wait for midnight UTC.
  2. 2Diagnostic Setting was deleted or disabled. Open the Cosmos account → MonitoringDiagnostic settings. If your nosqlstudio-monitoring setting is missing, someone removed it (a colleague, a stray terraform destroy, an Azure Policy). Re-run Stage 2 Step 7 / your CLI script / terraform apply to recreate it.

Concept

Forensic KQL — when did the data stop?

Open the workspace → Logs → paste and run: ``kusto CDBMongoRequests | where TimeGenerated > ago(24h) | summarize last_row = max(TimeGenerated), per_5min = count() by bin(TimeGenerated, 5m) | order by TimeGenerated desc The newest row's timestamp tells you exactly when the stream stopped. Pair with the **Activity log** on the Cosmos account (filter by Microsoft.Insights/diagnosticSettings/delete`) to find the operation that turned it off.

Step 20

“Log Analytics is connected, but MongoRequests table is empty”

This is NoSqlStudio's exact wording when it can authenticate to the workspace but finds zero rows. Three causes, in likelihood order:

  1. 1Diagnostic Setting routes to a different workspace than the one you pasted into NoSqlStudio. Open Diagnostic Settings on the Cosmos account → verify the target workspace matches.
  2. 2Resource-specific tables weren't picked (Stage 2 Step 7). The data IS landing, but in the legacy AzureDiagnostics table — NoSqlStudio doesn't query that one. Delete + recreate the Diagnostic Setting with the Resource specific destination type.
  3. 3Recent setup, no traffic yet. Logs need ~2-10 minutes of ingestion lag. Run a few queries against the Cosmos account, then wait.
Step 21

Brand-new Diagnostic Setting refuses to emit anything

Heads-up

Known Azure quirk — silent pipeline after delete + recreate

A fresh Diagnostic Setting sometimes refuses to start emitting events for 30+ minutes (or never), even though Azure reports it as active. This is a known quirk when a previous setting on the same resource was recently deleted, or when only a single log category is enabled.

1. Confirm you're stuck. Run the probe — either inside the workspace's Logs blade (just the KQL) or from your terminal. Replace <your-workspace-guid> with the GUID from Workspace → Overview → Workspace ID. If cnt stays at 0 for >10 minutes while the account is serving traffic, you ARE stuck.

bash·4 linhas
az monitor log-analytics query \
  --workspace <your-workspace-guid> \
  --analytics-query "CDBMongoRequests | where TimeGenerated > ago(10m) | summarize cnt=count()" \
  -o table

2. The workaround that unsticks it: delete the Diagnostic Setting and recreate it with three log categories enabled at the same time instead of just MongoRequests. The extra categories prime the diagnostic pipeline.

bash·12 linhas
RID="/subscriptions/<sub>/resourceGroups/<rg>/providers/Microsoft.DocumentDB/databaseAccounts/<acct>"
WS="/subscriptions/<sub>/resourceGroups/<rg>/providers/Microsoft.OperationalInsights/workspaces/<ws-name>"

az monitor diagnostic-settings delete --name nosqlstudio-monitoring --resource "$RID"

az monitor diagnostic-settings create \
  --name nosqlstudio-monitoring \
  --resource "$RID" \
  --workspace "$WS" \
  --logs '[{"category":"MongoRequests","enabled":true},{"category":"DataPlaneRequests","enabled":true},{"category":"QueryRuntimeStatistics","enabled":true}]' \
  --metrics '[{"category":"Requests","enabled":true}]' \
  --export-to-resource-specific true
See

After the recreate, re-run the KQL probe in step 1. Events typically appear within 3-7 minutes.

Concept

Once flowing, you can leave the three categories enabled (the extra two cost a bit more ingestion but give you query plan + raw request payloads in CDBQueryRuntimeStatistics and CDBDataPlaneRequests), or disable the extras after the pipeline warms up by re-running create with only MongoRequests.

When even the workaround doesn't work

  • Confirm the Cosmos account API is MongoDB: az cosmosdb show --ids "$RID" --query kind must print MongoDBMongoRequests only fires for that API.
  • Confirm the workspace region matches the Cosmos region — cross-region pipelines are slower and sometimes drop the first hour.
  • Check az monitor activity-log list --resource-id "$RID" --offset 1h for any failed diagnostic-setting operations.
  • Last resort: open an Azure support ticket — the diagnostic pipeline is fully Microsoft-managed.
Step 22

Rotating the client secret

Best practice is to rotate the SP's client secret every 12-24 months. To rotate:

  • Portal: Step 2's App Registration → Certificates & secrets → + New client secret → copy the new Value → paste into NoSqlStudio's Cloud Credentials → Save. Then delete the OLD secret from the same page.
  • Script: re-run setup-cosmos-monitoring.sh — it detects the existing SP and rotates the secret automatically (the old one stays valid; revoke it manually if you want).
  • Terraform: the time_rotating resource ticks every 2 years, so terraform apply after that point will refresh the secret. To force-rotate sooner: terraform taint module.cosmos_monitoring.time_rotating.secret[0] && terraform apply.

How to remove the monitoring overlay

Tearing down the monitoring stack never touches the Cosmos account itself — your data, throughput, and connection strings are unaffected.

Portal

  1. 1Cosmos account → Diagnostic settings → delete nosqlstudio-monitoring. Cosmos stops emitting logs.
  2. 2Resource group → IAM → revoke Monitoring Reader for the SP.
  3. 3Log Analytics workspace → IAM → revoke Log Analytics Reader for the SP.
  4. 4(Optional) Delete the Log Analytics workspace itself. Any retained data is dropped after the workspace's 14-day soft-delete window.
  5. 5(Optional) Microsoft Entra ID → App registrations → delete nosqlstudio-cosmos-monitoring. The SP and its secret are revoked.

CLI script

There's no built-in --destroy flag — Azure provides better tools. Run:

bash·6 linhas
RID="/subscriptions/.../databaseAccounts/my-cosmos-acct"
RG="$(echo $RID | awk -F/ '{print $5}')"

az monitor diagnostic-settings delete --name nosqlstudio-monitoring --resource $RID
az monitor log-analytics workspace delete --resource-group $RG --workspace-name nosqlstudio-monitoring --yes
az ad sp delete --id $(az ad sp list --display-name nosqlstudio-cosmos-monitoring --query '[0].id' -o tsv)

Terraform

bash·1 linha
terraform destroy

Heads-up

terraform destroy will recreate (and immediately destroy) the time_rotating secret if you've drifted past the rotation interval; this is harmless but produces a noisy plan.

Summary

PathTimeBest forRe-runnableReads cost cap
A — Azure Portal~25 min first timeOne-off, learning, audited environmentsManual (re-click)Manual (5 clicks)
B — CLI script~5 minSingle account, quick provisioningYes — idempotent--workspace-daily-cap-gb
C — Terraform module~5 min after initMultiple environments, IaC shops, drift detectionYes — by designlog_analytics_daily_quota_gb
When you're done, the Operations Center is your single pane of glass for the Cosmos account — RU consumption, throttles, latency, partition skew, cost, anomalies and a full DVR scrubber over the last 30 days of recorded snapshots. Open it from Tools → Cosmos Optimizer → Operations Center, and consider also reading the [Operations Center handbook](/docs/operations-center) to learn what the charts mean and how to act on each anomaly.