Decision
Application Insights, in the same resource group, on the free tier. A
Log Analytics workspace (log-theyard-ss, PerGB2018, 30-day retention) and
a component bound to it (appi-theyard-ss), both in RG-THEYARD-SS. The
daily ingestion cap is set to 0.1 GB with collection stopped at the cap, so
the resource cannot generate a charge even if something goes wrong.
The API sends with the Azure Monitor OpenTelemetry distro. One call in
Program.cs gives requests, dependencies and exceptions with their durations,
correlated by trace id. It is registered only when a connection string is
present. So a local run and every test are untouched and need no fake.
The connection string never enters the repository. It is an ingestion
key. The deploy workflow reads it from Azure at roll time with the federated
credential it already uses, masks it in the log, and substitutes it into the
container spec, which carries a __APPINSIGHTS_CONNECTION_STRING__
placeholder in the repository. The app treats any value starting with __
as absent, so a manual rollback with the committed file runs clean instead
of sending telemetry to nowhere.
That read is allowed to fail. If Azure does not answer, the roll leaves the
placeholder in place and logs a workflow warning, then ships anyway. Telemetry is
an addition to this system, not a dependency of it, and a delivery pipeline
that a monitoring resource can block is a worse trade than an hour of
missing traces.
Browser errors go through the API, not straight to Azure. The boundary
and the two window handlers already POST to /api/errors/client
(ADR: Error handling); that endpoint now also writes a structured log, which
the distro forwards. Three things follow: the page loads no second external
script, the ingestion key stays server-side, and a browser error is
searchable beside the server's own with the same trace correlation.
The Admin tab reads it back with the container's own identity.
id-theyard-ss was granted Monitoring Reader on the component, so the
container asks Application Insights about itself the same way it already
asks Azure Resource Manager about its own container group. No key is stored
for reading either.
In the code
The registration, and the reader it hands the Admin tab
(api/TheYard.Api/Program.cs):
string? telemetryConnection = builder.Configuration["APPLICATIONINSIGHTS_CONNECTION_STRING"];
bool telemetryOn = !string.IsNullOrWhiteSpace(telemetryConnection)
&& !telemetryConnection.StartsWith("__", StringComparison.Ordinal);
if (telemetryOn)
{
builder.Services.ConfigureOpenTelemetryTracerProvider(tracing => tracing.AddProcessor(new TelemetrySampling()));
builder.Services.ConfigureOpenTelemetryTracerProvider(tracing => tracing.AddSource(TelemetrySampling.ForemanSource));
builder.Services.AddOpenTelemetry().UseAzureMonitor(options =>
{
options.ConnectionString = telemetryConnection;
});
builder.Services.Configure<HttpClientTraceInstrumentationOptions>(options =>
{
options.RecordException = false;
options.EnrichWithException = TelemetrySampling.OnException;
});
builder.Services.Configure<AspNetCoreTraceInstrumentationOptions>(options => options.Filter = context => Traced(context.Request.Path, context.Request.Headers.UserAgent.ToString()));
foreach (string instrument in DroppedInstruments)
{
builder.Services.ConfigureOpenTelemetryMeterProvider(metrics => metrics.AddView(instrumentName: instrument, MetricStreamConfiguration.Drop));
}
builder.Logging.AddFilter<OpenTelemetryLoggerProvider>(CommandCategory, LogLevel.Warning);
}
var source = new TelemetrySource(
builder.Configuration["Azure:AppInsightsAppId"] ?? "6ff89351-7fcc-4a41-8238-db65c5903c36",
AzureIds.ClientId(builder.Configuration),
identity: identity);
builder.Services.AddSingleton(source);
builder.Services.AddSingleton(new TelemetryReader(source, enabled: telemetryOn, TimeProvider.System));
Live from api/TheYard.Api/Shared/Wiring/TelemetryRegistration.cs, region telemetry, read from this build at 99df7a8.
app.MapGet("/api/admin/telemetry", AdminCostRoutes.Telemetry);
Live from api/TheYard.Api/Features/Admin/Operations/AdminEndpoints.cs, region telemetry-endpoint, read from this build at 99df7a8.
One query answers the whole card, because three questions in three round
trips is three chances to time out (api/TheYard.Api/Shared/Observability/Telemetry.cs):
internal const string Query = """
let lookback = 1h;
let site_role = "__SITE__";
let summary = requests
| where timestamp > ago(lookback)
| where isempty(site_role) or cloud_RoleName =~ site_role
| summarize total = sum(itemCount), failed = sumif(itemCount, tostring(success) !in ("True", "true")),
p50 = percentile(duration, 50), p95 = percentile(duration, 95)
| extend part = "requests", p50 = round(p50, 1), p95 = round(p95, 1)
| project part, total, failed, p50, p95;
let slowest = requests
| where timestamp > ago(lookback)
| where isempty(site_role) or cloud_RoleName =~ site_role
| summarize calls = sum(itemCount), avg_ms = avg(duration) by route = name
| top 5 by avg_ms desc
| extend part = "slowest", avg_ms = round(avg_ms, 1)
| project part, route, calls, avg_ms;
let failures = exceptions
| where timestamp > ago(lookback)
| where isempty(site_role) or cloud_RoleName =~ site_role
| extend err_type = tostring(type), err_method = tostring(method)
| summarize hits = sum(itemCount), last_at = max(timestamp) by err_type, err_method
| top 5 by last_at desc
| extend part = "exception"
| project part, err_type, err_method, hits, last_at;
let browser = traces
| where timestamp > ago(lookback)
| where isempty(site_role) or cloud_RoleName =~ site_role
| where message startswith "Browser error on"
| summarize hits = sum(itemCount), last_at = max(timestamp)
| extend part = "browser"
| project part, hits, last_at;
let newest = requests
| where timestamp > ago(1d)
| where isempty(site_role) or cloud_RoleName =~ site_role
| summarize newest_at = max(timestamp)
| extend part = "newest"
| project part, newest_at;
union summary, slowest, failures, browser, newest
""";
internal static string QueryFor(string? siteName) => Query.Replace("__SITE__", siteName ?? "", StringComparison.Ordinal);
internal static string? SiteNameOrNull(string? name) =>
!string.IsNullOrWhiteSpace(name) && name.Length <= 60 && name.All(c => char.IsAsciiLetterOrDigit(c) || c == '-')
? name
: null;
internal static string ScopeFor(string? siteName) => siteName is null
? "Counts every site that reports to this Application Insights component: both sites share it, so these figures are both sites together."
: $"Counts {siteName} only. The other site reports to the same Application Insights component and is left out.";
Live from api/TheYard.Api/Shared/Observability/Telemetry.Kql.cs, region kql, read from this build at 99df7a8.
public async Task<object> GetRecentAsync(CancellationToken cancellation)
{
if (!Configured)
{
return new
{
configured = false,
note = "Application Insights is not configured for this build. It is wired at deploy time from Azure; a local run reports nothing.",
};
}
lock (_gate)
{
if (_cached is not null && clock.GetUtcNow() - _cachedAt < GoodFor)
{
return _cached;
}
}
return Keep(await source.AskAsync(cancellation));
}
Live from api/TheYard.Api/Shared/Observability/Telemetry.cs, region read, read from this build at 99df7a8.
Kusto answers in columns and rows; the card wants objects. Reading each row
by column name rather than position is what keeps a query edit from shifting
every value silently:
internal static object Shape(JsonDocument body, string? siteName)
{
var table = body.RootElement.GetProperty("tables")[0];
var columns = table.GetProperty("columns").EnumerateArray()
.Select((c, i) => (Name: c.GetProperty("name").GetString() ?? "", Index: i))
.ToDictionary(c => c.Name, c => c.Index, StringComparer.Ordinal);
string? Text(JsonElement row, string column) =>
columns.TryGetValue(column, out int i) && row[i].ValueKind is not JsonValueKind.Null
? row[i].ToString()
: null;
double? Number(JsonElement row, string column) =>
columns.TryGetValue(column, out int i) && row[i].ValueKind is JsonValueKind.Number
? row[i].GetDouble()
: null;
object? summary = null;
object? browser = null;
string? newest = null;
var slowest = new List<object>();
var exceptions = new List<object>();
foreach (var row in table.GetProperty("rows").EnumerateArray())
{
switch (Text(row, "part"))
{
case "requests":
summary = new
{
total = (int)(Number(row, "total") ?? 0),
failed = (int)(Number(row, "failed") ?? 0),
p50_ms = Number(row, "p50"),
p95_ms = Number(row, "p95"),
};
break;
case "slowest":
slowest.Add(new
{
name = Text(row, "route") ?? "",
calls = (int)(Number(row, "calls") ?? 0),
avg_ms = Number(row, "avg_ms"),
});
break;
case "exception":
exceptions.Add(new
{
type = Text(row, "err_type") ?? "",
method = Text(row, "err_method") ?? "",
count = (int)(Number(row, "hits") ?? 0),
last_at = Text(row, "last_at") ?? "",
});
break;
case "newest":
newest = Text(row, "newest_at");
break;
case "browser":
browser = new
{
count = (int)(Number(row, "hits") ?? 0),
last_at = Text(row, "last_at") ?? "",
};
break;
}
}
return new
{
configured = true,
available = true,
window = "the last hour",
site = siteName,
scope = TelemetryKql.ScopeFor(siteName),
summary = summary ?? new { total = 0, failed = 0, p50_ms = (double?)null, p95_ms = (double?)null },
slowest,
exceptions,
browser = browser ?? new { count = 0, last_at = "" },
newest_request_at = newest,
};
}
Live from api/TheYard.Api/Shared/Observability/Telemetry.Shape.cs, region shape, read from this build at 99df7a8.
The card, which renders every state the reader can answer with
(src/components/admin/TelemetryCard/TelemetryCard.tsx, a chunk of its own since the workbench):
{}
<article className={`${styles.card} op-glass`} data-testid="telemetry-card">
<h2 className={styles.cardTitle}>Traffic, last hour</h2>
{telemetry === null ? (
<CardState state="loading" />
) : telemetry === 'failed' ? (
failed('the telemetry')
) : !telemetry.configured || telemetry.available === false ? (
<p className={styles.muted} data-testid="telemetry-note">
{telemetry.note}
</p>
) : emptyHour !== null ? (
<>
{scopeLine(telemetry)}
<p className={styles.muted} data-testid="telemetry-empty">
{emptyHour}
</p>
</>
) : (
<>
{scopeLine(telemetry)}
<div className={styles.statusRow}>
<span className={pill((telemetry.summary?.failed ?? 0) === 0)}>
{telemetry.summary?.total ?? 0} request
{(telemetry.summary?.total ?? 0) === 1 ? '' : 's'}
</span>
<span className={styles.muted}>{telemetry.summary?.failed ?? 0} failed</span>
<span className={styles.mono}>p50 {reading(telemetry.summary?.p50_ms)}</span>
<span className={styles.mono}>p95 {reading(telemetry.summary?.p95_ms)}</span>
{/* Every React error counts, so the count of them is on the card
rather than only in the portal. */}
<span className={pill((telemetry.browser?.count ?? 0) === 0)}>
{telemetry.browser?.count ?? 0} browser
</span>
</div>
{telemetry.slowest && telemetry.slowest.length > 0 && (
<p className={styles.muted}>Slowest routes, by average time</p>
)}
<ul className={styles.checkList}>
{telemetry.slowest?.map((route) => (
<li key={route.name} className={styles.checkRow} data-testid="telemetry-route">
<span className={styles.mono}>{route.name}</span>
<span className={styles.duration}>avg {reading(route.avg_ms)}</span>
<span className={styles.muted}>
{route.calls} call{route.calls === 1 ? '' : 's'}
</span>
</li>
))}
</ul>
{telemetry.exceptions && telemetry.exceptions.length > 0 && (
<>
<p className={styles.muted}>Exceptions</p>
<ul className={styles.errorList}>
{telemetry.exceptions.map((entry, index) => (
<li key={index} className={styles.errorRow} data-testid="telemetry-exception">
<span className={styles.mono}>{entry.type}</span>
<span className={styles.muted}>{entry.method}</span>
<span className={styles.muted}>
{entry.count} time{entry.count === 1 ? '' : 's'}
</span>
</li>
))}
</ul>
</>
)}
</>
)}
</article>
Live from src/components/admin/TelemetryCard/TelemetryCard.tsx, region telemetry-card, read from this build at 99df7a8.
The container spec's placeholder, and the roll step that fills it in
(infra/aci-theyard.yaml, .github/workflows/deploy.yml):
The container group file this showed live retired on 19 October with the container groups' last settings (ADR: One web app for every .NET process); it is kept at infra/aci-theyard.yaml at 22b3015, the last commit that carried it.
- name: Roll the site
env:
YARD_AUTH_SIGNING_KEY: ${{ secrets.YARD_AUTH_SIGNING_KEY }}
ADMIN_KEY: ${{ secrets.ADMIN_KEY }}
NETLIFY_TOKEN: ${{ secrets.NETLIFY_TOKEN }}
LINKEDIN_CLIENT_ID: ${{ secrets.LINKEDIN_CLIENT_ID }}
LINKEDIN_CLIENT_SECRET: ${{ secrets.LINKEDIN_CLIENT_SECRET }}
run: |
# Resource Manager sometimes answers a write with a gateway error (BadGatewayConnection on
# 1.0.3.182's roll of the SQL site); each write is tried three times, a minute apart, before
# the roll is red, and the same write twice is the same setting (ADR: The deploy pipeline).
arm() { for try in 1 2 3; do "$@" && return 0; echo "::warning::Resource Manager refused $1 $2 $3 $4, try $try of 3"; [ "$try" = 3 ] || sleep 60; done; return 1; }
# The Application Insights connection string is an ingestion key, so it
# lives only in Azure: read it here with the credential this job already
# holds and mask it in the log. az resource show is core CLI; az monitor
# app-insights would pull an extension at run time, which is a second
# thing that can fail a deploy. Telemetry is an addition, not a
# dependency: if the read fails, the site keeps the value it has and
# still ships, because a deploy pipeline held hostage to its own
# observability is worse than a quiet hour of no traces.
CONN=$(az resource show -g "$RG" -n "$AI_NAME" \
--resource-type "Microsoft.Insights/components" \
--query "properties.ConnectionString" -o tsv 2>/dev/null || true)
if [ -n "$CONN" ]; then
echo "::add-mask::$CONN"
fi
# The database. The value names a server, a database and an
# authentication mode; the credential is the site's managed identity,
# which never leaves Azure. The name is composed rather than read back
# from Azure: the first version of this asked `az sql server show`,
# which this job's identity is not allowed to do, the call failed
# silently, and 1.0.0.49 shipped on SQLite and said so. An Azure SQL
# logical server's address is its name plus the service suffix. No
# Connect Timeout, on purpose: YardConnection widens a timeout nobody
# gave to sixty seconds, and a value given here wins over that
# (ADR: The SQL Server backend).
YARD_SQL=""
if [ -n "$SQL_SERVER" ]; then
YARD_SQL="Server=tcp:${SQL_SERVER}.database.windows.net,1433;Initial Catalog=${SQL_DB};Encrypt=True;TrustServerCertificate=False;Authentication=Active Directory Managed Identity;User Id=${MI_CLIENT_ID};"
fi
# #region secrets
# The session signing key and the operator's key, from the repository
# secrets of the same names, handed to the step through env and written
# to a file by python, so neither is ever part of a command line and
# neither appears in a log: GitHub masks them, and the settings call
# prints nothing. A value this job does not hold is left out, and the
# site keeps what it has: the template's placeholder on a new site,
# which the app reads as "no key", or the last roll's value
# (ADR: Three readers with no memory of the project; ADR: Site
# activity, and the line an address does not cross).
CONN="$CONN" YARD_SQL="$YARD_SQL" python3 - "$RUNNER_TEMP/settings.json" <<'PY'
import json, os, sys
wanted = {
"APPLICATIONINSIGHTS_CONNECTION_STRING": os.environ.get("CONN", ""),
"ConnectionStrings__YardSql": os.environ.get("YARD_SQL", ""),
"Auth__SigningKey": os.environ.get("YARD_AUTH_SIGNING_KEY", ""),
"Admin__Key": os.environ.get("ADMIN_KEY", ""),
}
# The Netlify token is optional: the edge card says in a sentence when
# it is missing, so an unset secret is a plain line here, not a warning
# (ADR: One frame for every resource).
# The LinkedIn app's two values are optional too: until they exist the LinkedIn
# posting card says "Not set up yet" (ADR: LinkedIn posting through the
# self-serve API).
optional = {
"Netlify__Token": os.environ.get("NETLIFY_TOKEN", ""),
"LinkedIn__ClientId": os.environ.get("LINKEDIN_CLIENT_ID", ""),
"LinkedIn__ClientSecret": os.environ.get("LINKEDIN_CLIENT_SECRET", ""),
}
held = [{"name": name, "value": value, "slotSetting": False} for name, value in {**wanted, **optional}.items() if value]
for name, value in wanted.items():
if not value:
print(f"::warning::{name} is not held by this job; the site keeps the value it has")
for name, value in optional.items():
if not value:
print(f"{name} is not set; the card that reads it says so")
json.dump(held, open(sys.argv[1], "w", encoding="utf-8"))
print(f"{len(held)} of {len(wanted) + len(optional)} values go to the site (values masked)")
PY
# #endregion secrets
if [ "$(cat "$RUNNER_TEMP/settings.json")" != "[]" ]; then
arm az webapp config appsettings set -g "$RG" -n "$APP" --settings "@$RUNNER_TEMP/settings.json" -o none
fi
rm -f "$RUNNER_TEMP/settings.json"
# The image is the only thing that changes between rolls. App Service
# starts the new container beside the old one and moves traffic when
# the new one answers, so the site serves through its own roll.
# It is pulled from GitHub's registry, which serves a public package to
# anyone, so the identity's registry pull is turned off in the same write
# and no credential is stored (ADR-009, the addendum on rolling from it).
arm az webapp config set -g "$RG" -n "$APP" --linux-fx-version "DOCKER|$GHCR_IMAGE" --generic-configurations '{"acrUseManagedIdentityCreds": false}' -o none
az webapp show -g "$RG" -n "$APP" --query "{state:state, image:siteConfig.linuxFxVersion, host:defaultHostName}" -o json
Live from .github/workflows/deploy.yml, region roll, read from this build at 99df7a8.