Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
30 changes: 20 additions & 10 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -1,32 +1,42 @@
name: Build and Test

on:
on:
workflow_dispatch:
push:
branches:
- main
paths:
- 'src/**'
- 'tests/**'
pull_request:
branches:
- main
paths:
- 'src/**'
- 'tests/**'

permissions:
contents: read

concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true

jobs:
build:
runs-on: ubuntu-latest

steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup dotnet
uses: actions/setup-dotnet@v4
with:
dotnet-version: 9.x
dotnet-version: |
10.x
11.x
- name: Build
run: dotnet build ci.slnf --configuration Release
- name: Test
run: dotnet test ci.slnf --configuration Release --no-build --no-restore --framework net9.0
run: dotnet test ci.slnf --configuration Release --no-build
- name: Pack
run: dotnet pack src/NimblePros.Metronome/NimblePros.Metronome.csproj --configuration Release --no-build --output artifacts
- name: Upload package
uses: actions/upload-artifact@v4
with:
name: nupkg
path: artifacts/*.nupkg
17 changes: 11 additions & 6 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
@@ -1,25 +1,30 @@
name: Release to Nuget

on:
on:
release:
types: [published]

permissions:
contents: read

jobs:
build:
runs-on: ubuntu-latest

steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup dotnet
uses: actions/setup-dotnet@v4
with:
dotnet-version: 9.x
dotnet-version: |
10.x
11.x
- name: Build
run: dotnet build ci.slnf --configuration Release
- name: Test
run: dotnet test ci.slnf --configuration Release --no-build --no-restore --framework net9.0
run: dotnet test ci.slnf --configuration Release --no-build
- name: Pack
run: dotnet pack ci.slnf --configuration Release --no-build --no-restore --output .
run: dotnet pack src/NimblePros.Metronome/NimblePros.Metronome.csproj --configuration Release --no-build --output artifacts
- name: Push to NuGet
run: dotnet nuget push "*.nupkg" --api-key ${{secrets.NUGET_API_KEY}} --source https://api.nuget.org/v3/index.json
run: dotnet nuget push "artifacts/*.nupkg" --api-key ${{ secrets.NUGET_API_KEY }} --source https://api.nuget.org/v3/index.json --skip-duplicate
17 changes: 14 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
# Metronome by NimblePros

[![Build and Test](https://github.com/NimblePros/Metronome/actions/workflows/ci.yml/badge.svg)](https://github.com/NimblePros/Metronome/actions/workflows/ci.yml)
[![NuGet](https://img.shields.io/nuget/v/NimblePros.Metronome.svg)](https://www.nuget.org/packages/NimblePros.Metronome)

A simple tool for tracking Database and Http calls per ASP.NET Core request.

Supports .NET 10 and .NET 11.

## Installation

Install the NuGet package:
Expand All @@ -14,7 +19,7 @@ dotnet add package NimblePros.Metronome

## Usage

Refer to the samples in the [samples](samples) directory.
Refer to the sample in the [sample](sample) directory.

### Wire up services

Expand Down Expand Up @@ -42,6 +47,8 @@ builder.Services.AddDbContext<ApplicationDbContext>((provider, options) =>
);
```

Use the `AddDbContext` overload that takes the service provider, as shown. `AddDbContextPool` and `AddDbContextFactory` aren't supported, because they build the options once and share them across requests.

### Dapper Query Tracking

Inject the scoped `DbCallCounter` and pass it as the first argument of a Dapper call. Calls are counted with any EF Core calls in the same request.
Expand All @@ -60,6 +67,8 @@ Available with sync and async versions: `Query<T>`, `QueryFirst<T>`, `QueryFirst

### HttpClient Tracking

Only calls made during a request are tracked. Calls made elsewhere, such as from a hosted service, are sent as usual without being counted.

```csharp
// simple named client
builder.Services.AddHttpClient("Foo")
Expand Down Expand Up @@ -90,9 +99,11 @@ info: NimblePros.Metronome.CombinedCallLoggingMiddleware[0]

### HTTP Headers

In addition, the information is added to a response header (unless configured not to do so):
In addition, the information is added to a `NimblePros.Metronome` response header:

![image](https://github.com/user-attachments/assets/a2076ab9-0808-4515-976f-1e6a13951568)
```
NimblePros.Metronome: DbCallCount=2;DbCallDuration=6.4678ms;HttpCallCount=1;HttpCallDuration=222.3137ms
```

## Using the Information

Expand Down
14 changes: 6 additions & 8 deletions sample/Metronome.Sample1/Metronome.Sample1.csproj
Original file line number Diff line number Diff line change
@@ -1,20 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>


<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore" Version="9.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="9.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Identity.UI" Version="9.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="9.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="9.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="9.0.0" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="9.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore" Version="10.0.15" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="10.0.15" />
<PackageReference Include="Microsoft.AspNetCore.Identity.UI" Version="10.0.15" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="10.0.15" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="10.0.15" />
</ItemGroup>

<ItemGroup>
Expand Down
36 changes: 25 additions & 11 deletions src/NimblePros.Metronome/CombinedCallLoggingMiddleware.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,16 @@
using Microsoft.AspNetCore.Http;
using System.Globalization;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;

namespace NimblePros.Metronome;

public class CombinedCallLoggingMiddleware
{
/// <summary>
/// The name of the response header that holds the call counts and durations for the request.
/// </summary>
public const string HeaderName = "NimblePros.Metronome";

private readonly RequestDelegate _next;

public CombinedCallLoggingMiddleware(RequestDelegate next)
Expand All @@ -19,22 +26,29 @@ public async Task InvokeAsync(
{
context.Response.OnStarting(() =>
{
string message = $"DbCallCount={dbCounter.CallCount};DbCallDuration={dbCounter.TotalTimeSpan.TotalMilliseconds}ms;HttpCallCount={httpCounter.CallCount};HttpCallDuration={httpCounter.TotalTimeSpan.TotalMilliseconds}ms HttpCallCount: {httpCounter.CallCount}";

context.Response.Headers.Add("NimblePros.Metronome", message);
context.Response.Headers[HeaderName] = FormatHeader(dbCounter, httpCounter);
return Task.CompletedTask;
});

await _next(context);
bool verbose = false; // TODO: Read from configuration
bool addHeader = true; // TODO: Read from configuration
if (dbCounter.CallCount > 0 || verbose)

if (dbCounter.CallCount > 0)
{
logger.LogInformation($"Database calls: {dbCounter.CallCount}, Total time: {dbCounter.TotalTimeSpan.TotalMilliseconds} ms");
logger.LogInformation("Database calls: {DbCallCount}, Total time: {DbCallDuration} ms",
dbCounter.CallCount, dbCounter.TotalTimeSpan.TotalMilliseconds);
}
if (httpCounter.CallCount > 0 || verbose)
if (httpCounter.CallCount > 0)
{
logger.LogInformation($"HTTP calls: {httpCounter.CallCount}, Total time: {httpCounter.TotalTimeSpan.TotalMilliseconds} ms");
logger.LogInformation("HTTP calls: {HttpCallCount}, Total time: {HttpCallDuration} ms",
httpCounter.CallCount, httpCounter.TotalTimeSpan.TotalMilliseconds);
}

}

/// <summary>
/// Formats the header value, for example <c>DbCallCount=2;DbCallDuration=6.4678ms;HttpCallCount=1;HttpCallDuration=222.3137ms</c>.
/// Numbers always use the invariant culture so the value parses the same way everywhere.
/// </summary>
internal static string FormatHeader(DbCallCounter dbCounter, HttpCallCounter httpCounter) =>
string.Create(CultureInfo.InvariantCulture,
$"DbCallCount={dbCounter.CallCount};DbCallDuration={dbCounter.TotalTimeSpan.TotalMilliseconds}ms;HttpCallCount={httpCounter.CallCount};HttpCallDuration={httpCounter.TotalTimeSpan.TotalMilliseconds}ms");
}
8 changes: 4 additions & 4 deletions src/NimblePros.Metronome/DbCallCountingInterceptor.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
using System.Data.Common;
using Microsoft.EntityFrameworkCore.Diagnostics;

using NimblePros.Metronome;
namespace NimblePros.Metronome;

public class DbCallCountingInterceptor : DbCommandInterceptor
{
Expand Down Expand Up @@ -50,10 +50,10 @@ public override async ValueTask<int> NonQueryExecutedAsync(
return await base.NonQueryExecutedAsync(command, eventData, result, cancellationToken);
}

public override object ScalarExecuted(
public override object? ScalarExecuted(
DbCommand command,
CommandExecutedEventData eventData,
object result)
object? result)
{
_counter.RecordCall(eventData.Duration);
return base.ScalarExecuted(command, eventData, result);
Expand All @@ -62,7 +62,7 @@ public override object ScalarExecuted(
public override async ValueTask<object?> ScalarExecutedAsync(
DbCommand command,
CommandExecutedEventData eventData,
object result,
object? result,
CancellationToken cancellationToken = default)
{
_counter.RecordCall(eventData.Duration);
Expand Down
16 changes: 14 additions & 2 deletions src/NimblePros.Metronome/HttpCallCounter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,18 @@

public class HttpCallCounter
{
public int CallCount { get; internal set; }
public TimeSpan TotalTimeSpan { get; internal set; }
private readonly object _lock = new();

public int CallCount { get; private set; }
public TimeSpan TotalTimeSpan { get; private set; }

// HTTP calls within a request often run concurrently (e.g. Task.WhenAll).
internal void RecordCall(TimeSpan duration)
{
lock (_lock)
{
CallCount++;
TotalTimeSpan += duration;
}
}
}
15 changes: 9 additions & 6 deletions src/NimblePros.Metronome/HttpCallCountingHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,18 @@ public HttpCallCountingHandler(IHttpContextAccessor accessor)
protected override async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
var counter = _accessor.HttpContext.RequestServices
.GetRequiredService<HttpCallCounter>();
// Handlers are created by IHttpClientFactory outside the request scope, so the request's
// counter is found through the current HttpContext. Calls made outside a request (hosted
// services, startup code) have no counter and are passed through untracked.
var counter = _accessor.HttpContext?.RequestServices.GetService<HttpCallCounter>();
if (counter is null)
{
return await base.SendAsync(request, cancellationToken);
}

var stopwatch = Stopwatch.StartNew();
var response = await base.SendAsync(request, cancellationToken);
stopwatch.Stop();

counter.CallCount++;
counter.TotalTimeSpan += stopwatch.Elapsed;
counter.RecordCall(stopwatch.Elapsed);

return response;
}
Expand Down
29 changes: 20 additions & 9 deletions src/NimblePros.Metronome/NimblePros.Metronome.csproj
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<TargetFrameworks>net10.0;net11.0</TargetFrameworks>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
Expand All @@ -18,9 +18,14 @@
<RepositoryUrl>https://github.com/NimblePros/Metronome</RepositoryUrl>
<PackageTags>performance metrics timing logging diagnostics dataaccess</PackageTags>
<PackageReleaseNotes>
* Now it's on net8
* Targets net10.0 and net11.0
* Adds Dapper extensions that track db calls
* AddMetronome() registers IHttpContextAccessor, so apps without Identity work
* HTTP calls made outside a request are no longer an error, and concurrent calls are all counted
* Fixes the format of the NimblePros.Metronome response header
* Moves DbCallCountingInterceptor into the NimblePros.Metronome namespace
</PackageReleaseNotes>
<Version>0.4.1</Version>
<Version>0.5.0</Version>
<AssemblyName>NimblePros.Metronome</AssemblyName>
<PackageIcon>icon.png</PackageIcon>
<PublishRepositoryUrl>true</PublishRepositoryUrl>
Expand All @@ -31,15 +36,21 @@


<ItemGroup>
<PackageReference Include="Dapper" Version="2.1.89" />
<PackageReference Include="Microsoft.AspNetCore.Http.Abstractions" Version="2.2.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Http" Version="8.0.0" />
<FrameworkReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Dapper" Version="2.1.100" />
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="10.0.404" PrivateAssets="All" />
</ItemGroup>

<ItemGroup Condition="'$(TargetFramework)' == 'net10.0'">
<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="10.0.0" />
</ItemGroup>

<ItemGroup Condition="'$(TargetFramework)' == 'net11.0'">
<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="11.0.0" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="8.0.0" PrivateAssets="All" />
<InternalsVisibleTo Include="NimblePros.Metronome.Tests" />
</ItemGroup>

<ItemGroup>
Expand Down
12 changes: 11 additions & 1 deletion src/NimblePros.Metronome/ServiceRegistrationExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,14 @@ public static class ServiceRegistrationExtensions
{
public static IServiceCollection AddMetronome(this IServiceCollection services)
{
// The HTTP handler finds the request's counter through the current HttpContext.
services.AddHttpContextAccessor();

services.AddScoped<DbCallCountingInterceptor>();
services.AddScoped<DbCallCounter>();

services.AddScoped<HttpCallCountingHandler>();
// IHttpClientFactory creates handlers in its own scope and caches them, so they are transient.
services.AddTransient<HttpCallCountingHandler>();
services.AddScoped<HttpCallCounter>();

return services;
Expand All @@ -21,6 +25,12 @@ public static IHttpClientBuilder AddMetronomeHandler(this IHttpClientBuilder bui
return builder.AddHttpMessageHandler<HttpCallCountingHandler>();
}

/// <summary>
/// Adds the interceptor that counts this request's database calls. Use it with
/// <c>AddDbContext((provider, options) =&gt; ...)</c>, which builds the options in the request scope.
/// It isn't supported with <c>AddDbContextPool</c> or <c>AddDbContextFactory</c>, whose options are
/// built once and shared across requests.
/// </summary>
public static DbContextOptionsBuilder AddMetronomeDbTracking(this DbContextOptionsBuilder builder, IServiceProvider provider)
{
return builder.AddInterceptors(provider.GetRequiredService<DbCallCountingInterceptor>());
Expand Down
Loading
Loading