Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
256ea2f
Adds FbTransactionInfo.GetTransactionId().
fdcastel Oct 25, 2024
7dd65e8
Adds .NET distributed tracing instrumentation.
fdcastel Oct 25, 2024
7fe1327
Add metrics.
fdcastel Oct 26, 2024
2968ea3
Fix NullReferenceException when StartActivity returns null
fdcastel Mar 23, 2026
9b25148
Fix Stopwatch elapsed time conversion
fdcastel Mar 23, 2026
c198a6a
Rename db.system to db.system.name per OTel semantic conventions v1.40+
fdcastel Mar 23, 2026
4781900
Set db.namespace attribute on spans from connection database name
fdcastel Mar 23, 2026
4f83e23
Set error.type attribute on failure spans
fdcastel Mar 23, 2026
78c6d3b
Gate db.query.text and db.query.parameter.* behind opt-in flags
fdcastel Mar 23, 2026
ecdb4cd
Read ActivitySource/Meter version from assembly metadata
fdcastel Mar 23, 2026
49382fb
Fix activity lifecycle: record metrics on error path, prevent stale r…
fdcastel Mar 23, 2026
594a23b
Remove non-standard and deprecated telemetry attributes
fdcastel Mar 23, 2026
f68747f
Add server.port, db.stored_procedure.name; fix server.address in metrics
fdcastel Mar 23, 2026
98f6f6d
Add db.query.summary and db.operation.name for Text commands
fdcastel Mar 23, 2026
4aa1e01
Add debug assertions in TraceCommandStop and TraceCommandException
fdcastel Mar 23, 2026
43d9462
Initialize MetricsConnectionAttributes to empty array
fdcastel Mar 23, 2026
425ae5a
Avoid dictionary allocation in observable metric callbacks
fdcastel Mar 23, 2026
395a907
Add InstrumentAdvice with histogram bucket boundaries on .NET 9+
fdcastel Mar 23, 2026
7402540
Add FbTelemetry public class with ActivitySource and Meter names
fdcastel Mar 23, 2026
36d884f
Add OpenTelemetry integration documentation
fdcastel Mar 23, 2026
ec1c68b
Fix IndexOfAny compilation on all target frameworks
fdcastel Mar 23, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 80 additions & 0 deletions docs/otel.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
# OpenTelemetry Integration

The Firebird ADO.NET provider includes built-in support for [OpenTelemetry](https://opentelemetry.io/) distributed tracing and metrics using the native .NET `System.Diagnostics` APIs. No dependency on the OpenTelemetry SDK is required in the provider itself — your application opts in by configuring the appropriate listeners.

## Distributed Tracing

The provider emits `Activity` spans for database command execution using `System.Diagnostics.ActivitySource`.

### Enabling Traces

```csharp
using OpenTelemetry.Trace;

var tracerProvider = Sdk.CreateTracerProviderBuilder()
.AddSource(FirebirdSql.Data.FirebirdClient.FbTelemetry.ActivitySourceName)
.AddConsoleExporter() // or any other exporter
.Build();
```

The `ActivitySource` name is `"FirebirdSql.Data"`, also available as the constant `FbTelemetry.ActivitySourceName`.

### Span Attributes

Spans follow the [OTel Database Client Semantic Conventions](https://opentelemetry.io/docs/specs/semconv/database/database-spans/):

| Attribute | Description |
|-----------|-------------|
| `db.system.name` | Always `"firebirdsql"` |
| `db.namespace` | The database name from the connection |
| `db.operation.name` | The SQL verb (`SELECT`, `INSERT`, etc.) or `EXECUTE PROCEDURE` |
| `db.collection.name` | The table name (for `TableDirect` commands) |
| `db.stored_procedure.name` | The stored procedure name (for `StoredProcedure` commands) |
| `db.query.summary` | A low-cardinality summary of the operation |
| `db.query.text` | The full SQL text (**opt-in**, see below) |
| `db.query.parameter.*` | Parameter values (**opt-in**, see below) |
| `server.address` | The database server hostname |
| `server.port` | The database server port (only when non-default, i.e. != 3050) |
| `error.type` | The SQLSTATE code (for `FbException`) or exception type name |

### Opt-In Sensitive Attributes

By default, `db.query.text` and `db.query.parameter.*` are **not** collected, as they may contain sensitive data. Enable them explicitly:

```csharp
using FirebirdSql.Data.Logging;

// Enable SQL text in traces
FbLogManager.EnableQueryTextTracing();

// Enable parameter values in traces (and logs)
FbLogManager.EnableParameterLogging();
```

## Metrics

The provider emits metrics via `System.Diagnostics.Metrics.Meter`.

### Enabling Metrics

```csharp
using OpenTelemetry.Metrics;

var meterProvider = Sdk.CreateMeterProviderBuilder()
.AddMeter(FirebirdSql.Data.FirebirdClient.FbTelemetry.MeterName)
.AddConsoleExporter() // or any other exporter
.Build();
```

The `Meter` name is `"FirebirdSql.Data"`, also available as the constant `FbTelemetry.MeterName`.

### Available Metrics

Metrics follow the [OTel Database Client Metrics Semantic Conventions](https://opentelemetry.io/docs/specs/semconv/database/database-metrics/):

| Metric | Type | Unit | Description |
|--------|------|------|-------------|
| `db.client.operation.duration` | Histogram | `s` | Duration of database client operations |
| `db.client.connection.create_time` | Histogram | `s` | Time to create a new connection |
| `db.client.connection.count` | ObservableUpDownCounter | `{connection}` | Current connection count by state (`idle`/`used`) |
| `db.client.connection.max` | ObservableUpDownCounter | `{connection}` | Maximum number of open connections allowed |
18 changes: 18 additions & 0 deletions src/FirebirdSql.Data.FirebirdClient.Tests/FbTransactionTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -139,4 +139,22 @@ public async Task SnapshotAtNumber()
}
}
}

[Test]
public async Task CanGetTransactionId()
{
if (!EnsureServerVersionAtLeast(new Version(2, 5, 0, 0)))
return;

await using (var transaction1 = await Connection.BeginTransactionAsync())
{
var idFromInfo = await new FbTransactionInfo(transaction1).GetTransactionIdAsync();
Assert.NotZero(idFromInfo);

var command = new FbCommand("SELECT current_transaction FROM rdb$database", Connection, transaction1);
var idFromSql = await command.ExecuteScalarAsync();

Assert.AreEqual(idFromInfo, idFromSql);
}
}
}
4 changes: 4 additions & 0 deletions src/FirebirdSql.Data.FirebirdClient/Common/IscHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,10 @@ public static List<object> ParseTransactionInfo(byte[] buffer, Charset charset)
case IscCodes.isc_info_error:
throw FbException.Create("Received error response.");

case IscCodes.isc_info_tra_id:
info.Add(VaxInteger(buffer, pos, length));
break;

case IscCodes.fb_info_tra_snapshot_number:
info.Add(VaxInteger(buffer, pos, length));
break;
Expand Down
140 changes: 104 additions & 36 deletions src/FirebirdSql.Data.FirebirdClient/FirebirdClient/FbCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,14 @@
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Diagnostics;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using FirebirdSql.Data.Common;
using FirebirdSql.Data.Logging;
using FirebirdSql.Data.Metrics;
using FirebirdSql.Data.Trace;
using Microsoft.Extensions.Logging;

namespace FirebirdSql.Data.FirebirdClient;
Expand All @@ -50,6 +53,8 @@ public sealed class FbCommand : DbCommand, IFbPreparedCommand, IDescriptorFiller
private int? _commandTimeout;
private int _fetchSize;
private Type[] _expectedColumnTypes;
private Activity _currentActivity;
private long _startedAtTicks;

#endregion

Expand Down Expand Up @@ -1064,7 +1069,10 @@ internal void Release()
_statement.Dispose2();
_statement = null;
}

TraceCommandStop();
}

Task IFbPreparedCommand.ReleaseAsync(CancellationToken cancellationToken) => ReleaseAsync(cancellationToken);
internal async Task ReleaseAsync(CancellationToken cancellationToken = default)
{
Expand All @@ -1082,6 +1090,8 @@ internal async Task ReleaseAsync(CancellationToken cancellationToken = default)
await _statement.Dispose2Async(cancellationToken).ConfigureAwait(false);
_statement = null;
}

TraceCommandStop();
}

void IFbPreparedCommand.TransactionCompleted() => TransactionCompleted();
Expand Down Expand Up @@ -1302,6 +1312,48 @@ private async ValueTask UpdateParameterValuesAsync(Descriptor descriptor, Cancel

#endregion

#region Tracing

private void TraceCommandStart()
{
Debug.Assert(_currentActivity == null);
if (FbActivitySource.Source.HasListeners())
_currentActivity = FbActivitySource.CommandStart(this);

_startedAtTicks = FbMetricsStore.CommandStart();
}

private void TraceCommandStop()
{
Debug.Assert(_startedAtTicks > 0 || _currentActivity == null, "TraceCommandStop called without TraceCommandStart");

if (_currentActivity != null)
{
// Do not set status to Ok: https://opentelemetry.io/docs/concepts/signals/traces/#span-status
_currentActivity.Dispose();
_currentActivity = null;
}

FbMetricsStore.CommandStop(_startedAtTicks, Connection);
_startedAtTicks = 0;
}

private void TraceCommandException(Exception e)
{
Debug.Assert(_startedAtTicks > 0 || _currentActivity == null, "TraceCommandException called without TraceCommandStart");

if (_currentActivity != null)
{
FbActivitySource.CommandException(_currentActivity, e);
_currentActivity = null;
}

FbMetricsStore.CommandStop(_startedAtTicks, Connection);
_startedAtTicks = 0;
}

#endregion Tracing

#region Private Methods

private void Prepare(bool returnsSet)
Expand Down Expand Up @@ -1446,57 +1498,73 @@ private async Task PrepareAsync(bool returnsSet, CancellationToken cancellationT
private void ExecuteCommand(CommandBehavior behavior, bool returnsSet)
{
LogMessages.CommandExecution(Log, this);
TraceCommandStart();
try
{
Prepare(returnsSet);

Prepare(returnsSet);
if ((behavior & CommandBehavior.SequentialAccess) == CommandBehavior.SequentialAccess ||
(behavior & CommandBehavior.SingleResult) == CommandBehavior.SingleResult ||
(behavior & CommandBehavior.SingleRow) == CommandBehavior.SingleRow ||
(behavior & CommandBehavior.CloseConnection) == CommandBehavior.CloseConnection ||
behavior == CommandBehavior.Default)
{
// Set the fetch size
_statement.FetchSize = _fetchSize;

if ((behavior & CommandBehavior.SequentialAccess) == CommandBehavior.SequentialAccess ||
(behavior & CommandBehavior.SingleResult) == CommandBehavior.SingleResult ||
(behavior & CommandBehavior.SingleRow) == CommandBehavior.SingleRow ||
(behavior & CommandBehavior.CloseConnection) == CommandBehavior.CloseConnection ||
behavior == CommandBehavior.Default)
{
// Set the fetch size
_statement.FetchSize = _fetchSize;
// Set if it's needed the Records Affected information
_statement.ReturnRecordsAffected = _connection.ConnectionOptions.ReturnRecordsAffected;

// Set if it's needed the Records Affected information
_statement.ReturnRecordsAffected = _connection.ConnectionOptions.ReturnRecordsAffected;
// Validate input parameter count
if (_namedParameters.Count > 0 && !HasParameters)
{
throw FbException.Create("Must declare command parameters.");
}

// Validate input parameter count
if (_namedParameters.Count > 0 && !HasParameters)
{
throw FbException.Create("Must declare command parameters.");
// Execute
_statement.Execute(CommandTimeout * 1000, this);
}

// Execute
_statement.Execute(CommandTimeout * 1000, this);
}
catch (Exception e)
{
TraceCommandException(e);
throw;
}
}
private async Task ExecuteCommandAsync(CommandBehavior behavior, bool returnsSet, CancellationToken cancellationToken = default)
{
LogMessages.CommandExecution(Log, this);
TraceCommandStart();
try
{
await PrepareAsync(returnsSet, cancellationToken).ConfigureAwait(false);

await PrepareAsync(returnsSet, cancellationToken).ConfigureAwait(false);
if ((behavior & CommandBehavior.SequentialAccess) == CommandBehavior.SequentialAccess ||
(behavior & CommandBehavior.SingleResult) == CommandBehavior.SingleResult ||
(behavior & CommandBehavior.SingleRow) == CommandBehavior.SingleRow ||
(behavior & CommandBehavior.CloseConnection) == CommandBehavior.CloseConnection ||
behavior == CommandBehavior.Default)
{
// Set the fetch size
_statement.FetchSize = _fetchSize;

if ((behavior & CommandBehavior.SequentialAccess) == CommandBehavior.SequentialAccess ||
(behavior & CommandBehavior.SingleResult) == CommandBehavior.SingleResult ||
(behavior & CommandBehavior.SingleRow) == CommandBehavior.SingleRow ||
(behavior & CommandBehavior.CloseConnection) == CommandBehavior.CloseConnection ||
behavior == CommandBehavior.Default)
{
// Set the fetch size
_statement.FetchSize = _fetchSize;
// Set if it's needed the Records Affected information
_statement.ReturnRecordsAffected = _connection.ConnectionOptions.ReturnRecordsAffected;

// Set if it's needed the Records Affected information
_statement.ReturnRecordsAffected = _connection.ConnectionOptions.ReturnRecordsAffected;
// Validate input parameter count
if (_namedParameters.Count > 0 && !HasParameters)
{
throw FbException.Create("Must declare command parameters.");
}

// Validate input parameter count
if (_namedParameters.Count > 0 && !HasParameters)
{
throw FbException.Create("Must declare command parameters.");
// Execute
await _statement.ExecuteAsync(CommandTimeout * 1000, this, cancellationToken).ConfigureAwait(false);
}

// Execute
await _statement.ExecuteAsync(CommandTimeout * 1000, this, cancellationToken).ConfigureAwait(false);
}
catch (Exception e)
{
TraceCommandException(e);
throw;
}
}

Expand Down
16 changes: 16 additions & 0 deletions src/FirebirdSql.Data.FirebirdClient/FirebirdClient/FbConnection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,15 @@
//$Authors = Carlos Guzman Alvarez, Jiri Cincura (jiri@cincura.net)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Threading;
using System.Threading.Tasks;
using FirebirdSql.Data.Common;
using FirebirdSql.Data.Logging;
using FirebirdSql.Data.Metrics;
using Microsoft.Extensions.Logging;

namespace FirebirdSql.Data.FirebirdClient;
Expand Down Expand Up @@ -190,6 +192,13 @@ public override string ConnectionString
_options = new ConnectionString(value);
_options.Validate();
_connectionString = value;

MetricsConnectionAttributes = [
new("db.system.name", "firebirdsql"),
new("db.namespace", _options.Database),
new("server.address", _options.DataSource),
new("server.port", _options.Port),
];
}
}
}
Expand Down Expand Up @@ -270,6 +279,8 @@ internal bool IsClosed
get { return _state == ConnectionState.Closed; }
}

internal KeyValuePair<string, object>[] MetricsConnectionAttributes = [];

#endregion

#region Protected Properties
Expand Down Expand Up @@ -524,6 +535,7 @@ public override async Task ChangeDatabaseAsync(string databaseName, Cancellation
public override void Open()
{
LogMessages.ConnectionOpening(Log, this);
var startedAtTicks = FbMetricsStore.ConnectionOpening();

if (string.IsNullOrEmpty(_connectionString))
{
Expand Down Expand Up @@ -616,10 +628,13 @@ public override void Open()
}

LogMessages.ConnectionOpened(Log, this);
FbMetricsStore.ConnectionOpened(startedAtTicks, this._options.NormalizedConnectionString);
}

public override async Task OpenAsync(CancellationToken cancellationToken)
{
LogMessages.ConnectionOpening(Log, this);
var startedAtTicks = FbMetricsStore.ConnectionOpening();

if (string.IsNullOrEmpty(_connectionString))
{
Expand Down Expand Up @@ -712,6 +727,7 @@ public override async Task OpenAsync(CancellationToken cancellationToken)
}

LogMessages.ConnectionOpened(Log, this);
FbMetricsStore.ConnectionOpened(startedAtTicks, this._options.NormalizedConnectionString);
}

public override void Close()
Expand Down
Loading
Loading