Path: redb/redb.Core/Diagnostics/RedbTelemetry.cs
Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb
Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/Diagnostics/RedbTelemetry.cs
----
using System;
using System.Diagnostics;
using System.Threading.Tasks;
namespace redb.Core.Diagnostics;
///
/// Wraps one database command in an on .
/// The span carries the operation name and the database system only, never the statement text or the
/// parameters (they may hold secrets or personal data). A command that throws marks the span an error,
/// a caller's cancellation does not; either way the exception is rethrown unchanged. When nothing
/// subscribes, the caller runs the connection directly: no span, no extra allocation.
///
internal static class RedbTelemetry
{
/// Value of the db.system tag on every REDB span.
public const string System = "redb";
/// A read returning rows or scalars.
public const string Query = "query";
/// A single scalar read.
public const string Scalar = "scalar";
/// A write (INSERT, UPDATE, DELETE).
public const string Execute = "execute";
/// A raw call returning JSON.
public const string Json = "json";
/// Whether anything subscribes to the source; when false a wrapper is a no-op and skipped.
public static bool Enabled => RedbActivitySource.Source.HasListeners();
/// Runs inside a span named for .
public static async Task RunAsync(string operation, Func> action)
{
using var activity = Start(operation);
try
{
return await action().ConfigureAwait(false);
}
catch (Exception ex)
{
Fail(activity, ex);
throw;
}
}
/// Runs inside a span named for .
public static async Task RunAsync(string operation, Func action)
{
using var activity = Start(operation);
try
{
await action().ConfigureAwait(false);
}
catch (Exception ex)
{
Fail(activity, ex);
throw;
}
}
private static Activity? Start(string operation)
{
var activity = RedbActivitySource.Source.StartActivity($"redb.{operation}", ActivityKind.Internal);
if (activity is { IsAllDataRequested: true })
{
activity.SetTag("db.system", System);
activity.SetTag("db.operation", operation);
}
return activity;
}
private static void Fail(Activity? activity, Exception ex)
{
if (activity is null)
return;
// The exception is always recorded; only the error status is withheld for a caller's
// cancellation, which is not a failure of the database.
activity.AddException(ex);
if (ex is not OperationCanceledException)
activity.SetStatus(ActivityStatusCode.Error, ex.Message);
}
}