npgsql / npgsql

Npgsql is the .NET data provider for PostgreSQL.
http://www.npgsql.org
PostgreSQL License
3.27k stars 822 forks source link

Missing EventCounter when using Npgsql.DependencyInjection #4798

Open lklein53 opened 1 year ago

lklein53 commented 1 year ago

Hi together,

We are using the Npgsql.DependencyInjection to inject a NpgsqlDataSource into the ServiceCollection. With this approach the event counter for idle and busy connections are missing and the number of connection pools is 0.

Steps to reproduce

Use the Npgsql.DependencyInjection package and use builder.Services.AddNpgsqlDataSource("Host=pg_server;Username=test;Password=test;Database=test"); to inject a NpgsqlDataSource. Use this data source to create a connection and collect the metrics via dotnet counters monitor Npgsql -p <PID>

The issue

We noticed that the EventCounter for Idle Connections, Busy Connections are missing and that the counter for Connection Pools is always 0.

Further technical details

I think the issue is that NpgsqlEventSource.Log.DataSourceCreated(newDataSource); is only called from SetupDataSource and not from the NpgsqlDataSourceBuilder.

Thanks for your help and kind regards, Lars

elafarge commented 9 months ago

I've run into a similar issue today and am proposing a (maybe naive ?) fix here: https://github.com/npgsql/npgsql/pull/5497

42ama commented 1 week ago

I'd like to see that change, too.

42ama commented 6 days ago

I have another case of reproducing the problem. It reproduces on both the current version of the library and the version with the fix from #5497.

Case in project.

Reproduction Steps:

  1. Go to the sources of the Npgsql.NpgsqlEventSource class.
  2. Put a breakpoint in the DataSourceCreated and OnEventCommand methods.
  3. In debug mode, start the application and make a request to GetWeatherForecast.

Expected result: The execution thread first stopped in the DataSourceCreated method, then moved to OnEventCommand, idle-connections and busy-connections metrics were registered.

Factual result (both with and without the fix from https://github.com/npgsql/npgsql/pull/5497): The execution thread stops in the OnEventCommand method, then stops in the DataSourceCreated method. It does not come to OnEventCommand anymore, so after _dataSources initiation there is no re-registration of metrics collection, because OnEventCommand is not called again.

Also in the NpgSqlMeter class you can put a breakpoint in the SaveMeasurements method to see what metrics values are written to _values. There are no values related to idle-connections and busy-connections.

FYI @elafarge