Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Renamed default LatencySLI to ServiceLevelIndicator #34

Merged
merged 6 commits into from
Mar 29, 2024
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
19 changes: 14 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,17 +23,17 @@ By tracking SLIs over time, service providers can identify trends and make impro

## Service Level Indicator Library

Service Level Indicator library will help emit latency metrics for each API operation to help monitor the service performance over time.
**ServiceLevelIndicators** library will help emit latency metrics for each API operation to help monitor the service performance over time.
The metrics is emitted via standard [.NET Meter Class](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.metrics.meter?view=net-7.0).

By default, an instrument named `LatencySLI` is added to the service metrics and the metrics are emitted. The metrics are emitted with the following [attributes](https://opentelemetry.io/docs/specs/otel/common/#attribute).
By default, an instrument named `ServiceLevelIndicator` is added to the service metrics and the metrics are emitted. The metrics are emitted with the following [attributes](https://opentelemetry.io/docs/specs/otel/common/#attribute).

- CustomerResourceId - A value that helps identity the customer, customer group or calling service.
- LocationId - The location where the service running. eg. Public cloud, West US 3 region.
- Operation - The name of the operation.
- activity.status_code - The activity status code is set based on the success or failure of the operation. [ActivityStatusCode](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.activitystatuscode?view=net-7.0).
- activity.status.code - The activity status code is set based on the success or failure of the operation. [ActivityStatusCode](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.activitystatuscode?view=net-7.0).

ServiceLevelIndicators.Asp adds the following dimensions.
**ServiceLevelIndicators.Asp** adds the following dimensions.

- Operation - In ASP.NET the operation name defaults to `AttributeRouteInfo.Template` information like `GET Weatherforecast`.
- The activity status code will be
Expand All @@ -43,9 +43,18 @@ ServiceLevelIndicators.Asp adds the following dimensions.
- http.response.status_code - The http status code.
- http.request.method (Optional)- The http request method (GET, POST, etc) is added.

ServiceLevelIndicators.Asp.Versioning adds the following dimensions.
Difference between ServiceLevelIndicator and http.server.request.duration

| | ServiceLevelIndicator | http.server.request.duration
| ---------- | ------- | ------
| Resolution | milliseconds | seconds
| Customer | CustomerResourceId | N/A
| Error check | Activity or HTTP status.code | HTTP status code

**ServiceLevelIndicators.Asp.Versioning** adds the following dimensions.
- http.api.version - The API Version when used in conjunction with [API Versioning package](https://github.com/dotnet/aspnet-api-versioning).


## NuGet Packages

- **ServiceLevelIndicators**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,8 @@ public async Task SLI_Metrics_is_emitted_with_API_version_as_query_parameter()
new("CustomerResourceId", "TestCustomerResourceId"),
new("LocationId", "ms-loc://az/public/West US 3"),
new("Operation", "GET TestSingle"),
new("activity.status_code", "Ok"),
new("http.response.status_code", 200),
new("activity.status.code", "Ok"),
new("http.response.status.code", 200),
new("http.api.version", "2023-08-29"),
];
using var host = await CreateHost();
Expand All @@ -73,8 +73,8 @@ public async Task SLI_Metrics_is_emitted_with_API_version_as_header()
new("CustomerResourceId", "TestCustomerResourceId"),
new("LocationId", "ms-loc://az/public/West US 3"),
new("Operation", "GET TestSingle"),
new("activity.status_code", "Ok"),
new("http.response.status_code", 200),
new("activity.status.code", "Ok"),
new("http.response.status.code", 200),
new("http.api.version", "2023-08-29"),
];
using var host = await CreateHost();
Expand All @@ -99,8 +99,8 @@ public async Task SLI_Metrics_is_emitted_with_neutral_API_version()
new("CustomerResourceId", "TestCustomerResourceId"),
new("LocationId", "ms-loc://az/public/West US 3"),
new("Operation", "GET TestNeutral"),
new("activity.status_code", "Ok"),
new("http.response.status_code", 200),
new("activity.status.code", "Ok"),
new("http.response.status.code", 200),
];
using var host = await CreateHost();

Expand All @@ -122,8 +122,8 @@ public async Task SLI_Metrics_is_emitted_with_default_API_version()
new("CustomerResourceId", "TestCustomerResourceId"),
new("LocationId", "ms-loc://az/public/West US 3"),
new("Operation", "GET TestSingle"),
new("activity.status_code", "Ok"),
new("http.response.status_code", 200),
new("activity.status.code", "Ok"),
new("http.response.status.code", 200),
];
using var host = await CreateHostWithDefaultApiVersion();

Expand Down Expand Up @@ -160,8 +160,8 @@ public async Task SLI_Metrics_is_emitted_when_api_version_is_invalid(string rout
new("CustomerResourceId", "TestCustomerResourceId"),
new("LocationId", "ms-loc://az/public/West US 3"),
new("Operation", "GET /" + route),
new("activity.status_code", "Unset"),
new("http.response.status_code", 400),
new("activity.status.code", "Unset"),
new("http.response.status.code", 400),
];
var routeWithVersion = route + "?" + version;
using var host = await CreateHost();
Expand Down Expand Up @@ -262,7 +262,7 @@ private void OnMeasurementRecorded(Instrument instrument, long measurement, Read
_callbackCalled = true;

_output.WriteLine($"Measurement {measurement}");
instrument.Name.Should().Be("LatencySLI");
instrument.Name.Should().Be("ServiceLevelIndicator");
instrument.Unit.Should().Be("ms");
measurement.Should().BeInRange(MillisecondsDelay - 10, MillisecondsDelay + 400);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ private static void SetCustomerResourceIdFromAttribute(HttpContext context, Endp
private static void UpdateOperationWithResponseStatus(HttpContext context, MeasuredOperationLatency measuredOperation)
{
var statusCode = context.Response.StatusCode;
measuredOperation.AddAttribute("http.response.status_code", statusCode);
measuredOperation.AddAttribute("http.response.status.code", statusCode);
var activityCode = statusCode switch
{
>= StatusCodes.Status500InternalServerError => ActivityStatusCode.Error,
Expand Down
42 changes: 21 additions & 21 deletions ServiceLevelIndicators.Asp/tests/ServiceLevelIndicatorAspTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,8 @@ void OnMeasurementRecorded(Instrument instrument, long measurement, ReadOnlySpan
new("CustomerResourceId", "TestCustomerResourceId"),
new("LocationId", "ms-loc://az/public/West US 3"),
new("Operation", "GET Test"),
new("activity.status_code", "Ok"),
new("http.response.status_code", 200),
new("activity.status.code", "Ok"),
new("http.response.status.code", 200),
};

ValidateMetrics(instrument, measurement, tags, expectedTags);
Expand All @@ -75,8 +75,8 @@ void OnMeasurementRecorded(Instrument instrument, long measurement, ReadOnlySpan
new("CustomerResourceId", "TestCustomerResourceId"),
new("LocationId", "ms-loc://az/public/West US 3"),
new("Operation", "POST Test"),
new("activity.status_code", "Ok"),
new("http.response.status_code", 200),
new("activity.status.code", "Ok"),
new("http.response.status.code", 200),
};

ValidateMetrics(instrument, measurement, tags, expectedTags);
Expand All @@ -103,8 +103,8 @@ void OnMeasurementRecorded(Instrument instrument, long measurement, ReadOnlySpan
new("CustomerResourceId", "TestCustomerResourceId"),
new("LocationId", "ms-loc://az/public/West US 3"),
new("Operation", "GET Test/bad_request"),
new("activity.status_code", "Unset"),
new("http.response.status_code", 400),
new("activity.status.code", "Unset"),
new("http.response.status.code", 400),
};

ValidateMetrics(instrument, measurement, tags, expectedTags);
Expand Down Expand Up @@ -133,9 +133,9 @@ void OnMeasurementRecorded(Instrument instrument, long measurement, ReadOnlySpan
new("CustomerResourceId", "xavier@somewhere.com"),
new("LocationId", "ms-loc://az/public/West US 3"),
new("Operation", "GET Test"),
new("activity.status_code", "Ok"),
new("activity.status.code", "Ok"),
new("http.request.method", "GET"),
new("http.response.status_code", 200),
new("http.response.status.code", 200),
new("foo", "bar"),
new("test", "again"),
new("enrichAsync", "async"),
Expand Down Expand Up @@ -165,8 +165,8 @@ void OnMeasurementRecorded(Instrument instrument, long measurement, ReadOnlySpan
new("CustomerResourceId", "TestCustomerResourceId"),
new("LocationId", "ms-loc://az/public/West US 3"),
new("Operation", "TestOperation"),
new("activity.status_code", "Ok"),
new("http.response.status_code", 200),
new("activity.status.code", "Ok"),
new("http.response.status.code", 200),
};

ValidateMetrics(instrument, measurement, tags, expectedTags);
Expand All @@ -193,8 +193,8 @@ void OnMeasurementRecorded(Instrument instrument, long measurement, ReadOnlySpan
new("CustomerResourceId", "myId"),
new("LocationId", "ms-loc://az/public/West US 3"),
new("Operation", "GET Test/customer_resourceid/{id}"),
new("activity.status_code", "Ok"),
new("http.response.status_code", 200),
new("activity.status.code", "Ok"),
new("http.response.status.code", 200),
};

ValidateMetrics(instrument, measurement, tags, expectedTags);
Expand All @@ -221,8 +221,8 @@ void OnMeasurementRecorded(Instrument instrument, long measurement, ReadOnlySpan
new("CustomerResourceId", "TestCustomerResourceId"),
new("LocationId", "ms-loc://az/public/West US 3"),
new("Operation", "GET Test/custom_attribute/{value}"),
new("activity.status_code", "Ok"),
new("http.response.status_code", 200),
new("activity.status.code", "Ok"),
new("http.response.status.code", 200),
new("CustomAttribute", "Mickey"),
};

Expand Down Expand Up @@ -274,8 +274,8 @@ void OnMeasurementRecorded(Instrument instrument, long measurement, ReadOnlySpan
new("CustomerResourceId", "TestCustomerResourceId"),
new("LocationId", "ms-loc://az/public/West US 3"),
new("Operation", "GET Test/send_sli"),
new("activity.status_code", "Ok"),
new("http.response.status_code", 200),
new("activity.status.code", "Ok"),
new("http.response.status.code", 200),
};

ValidateMetrics(instrument, measurement, tags, expectedTags);
Expand Down Expand Up @@ -330,8 +330,8 @@ void OnMeasurementRecorded(Instrument instrument, long measurement, ReadOnlySpan
new("CustomerResourceId", "TestCustomerResourceId"),
new("LocationId", "ms-loc://az/public/West US 3"),
new("Operation", "GET Test/try_get_measured_operation_latency/{value}"),
new("activity.status_code", "Ok"),
new("http.response.status_code", 200),
new("activity.status.code", "Ok"),
new("http.response.status.code", 200),
new("CustomAttribute", "Goofy"),
};

Expand Down Expand Up @@ -361,8 +361,8 @@ void OnMeasurementRecorded(Instrument instrument, long measurement, ReadOnlySpan
new("age", "25"),
new("LocationId", "ms-loc://az/public/West US 3"),
new("Operation", "GET Test/name/{first}/{surname}/{age}"),
new("activity.status_code", "Ok"),
new("http.response.status_code", 200),
new("activity.status.code", "Ok"),
new("http.response.status.code", 200),
};

ValidateMetrics(instrument, measurement, tags, expectedTags);
Expand Down Expand Up @@ -404,7 +404,7 @@ public void Dispose()
private void ValidateMetrics(Instrument instrument, long measurement, ReadOnlySpan<KeyValuePair<string, object?>> tags, KeyValuePair<string, object?>[] expectedTags)
{
_callbackCalled = true;
instrument.Name.Should().Be("LatencySLI");
instrument.Name.Should().Be("ServiceLevelIndicator");
instrument.Unit.Should().Be("ms");
measurement.Should().BeInRange(TestHostBuilder.MillisecondsDelay - 10, TestHostBuilder.MillisecondsDelay + 400);
_output.WriteLine($"Measurement {measurement}");
Expand Down
1 change: 0 additions & 1 deletion ServiceLevelIndicators.Asp/tests/TestHostBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Primitives;

internal class TestHostBuilder
{
Expand Down
7 changes: 7 additions & 0 deletions ServiceLevelIndicators.sln
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ServiceLevelIndicators.Asp.
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SampleMinimalApiSli", "sample\MinApi\SampleMinimalApiSli.csproj", "{D25F951D-CE1A-47D1-8421-F71BEBF3A356}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GenerateSli", "sample\GenerateSli\GenerateSli.csproj", "{94FA59E4-26A3-4457-8AD7-4091205F1D06}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -79,6 +81,10 @@ Global
{D25F951D-CE1A-47D1-8421-F71BEBF3A356}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D25F951D-CE1A-47D1-8421-F71BEBF3A356}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D25F951D-CE1A-47D1-8421-F71BEBF3A356}.Release|Any CPU.Build.0 = Release|Any CPU
{94FA59E4-26A3-4457-8AD7-4091205F1D06}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{94FA59E4-26A3-4457-8AD7-4091205F1D06}.Debug|Any CPU.Build.0 = Debug|Any CPU
{94FA59E4-26A3-4457-8AD7-4091205F1D06}.Release|Any CPU.ActiveCfg = Release|Any CPU
{94FA59E4-26A3-4457-8AD7-4091205F1D06}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand All @@ -93,6 +99,7 @@ Global
{B3F4A43C-64C1-4A41-99DC-0864BB30479C} = {2C6E9F62-8968-455A-AD02-DC795296471A}
{A776B107-2730-4EB6-B481-7F3EFAC2A2A8} = {2C6E9F62-8968-455A-AD02-DC795296471A}
{D25F951D-CE1A-47D1-8421-F71BEBF3A356} = {A7D8DEF7-8D37-4DE9-B935-7D9FF571132B}
{94FA59E4-26A3-4457-8AD7-4091205F1D06} = {A7D8DEF7-8D37-4DE9-B935-7D9FF571132B}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {5C1087B8-93AA-4847-9D18-6A16E754593F}
Expand Down
6 changes: 3 additions & 3 deletions ServiceLevelIndicators/src/ServiceLevelIndicatorOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public class ServiceLevelIndicatorOptions
/// CustomerResrouceId is the unique identifier for the customer like subscriptionId, tenantId, etc.
/// CustomerResourceId can be set for the entire service here or in each API method.
/// </summary>
public string CustomerResourceId { get; set; } = string.Empty;
public string CustomerResourceId { get; set; } = "Unset";

/// <summary>
/// Location where the service is running.
Expand All @@ -27,13 +27,13 @@ public class ServiceLevelIndicatorOptions
/// <summary>
/// The instrument name created on the given meter. Cannot be null.
/// </summary>
public string InstrumentName { get; set; } = "LatencySLI";
public string InstrumentName { get; set; } = "ServiceLevelIndicator";

/// <summary>
/// Activity Status Code attribute name.
/// [ActivityStatusCode](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.activitystatuscode?view=net-7.0)
/// </summary>
public string ActivityStatusCodeAttributeName { get; set; } = "activity.status_code";
public string ActivityStatusCodeAttributeName { get; set; } = "activity.status.code";

/// <summary>
/// Automatically emit for all API methods.
Expand Down
4 changes: 2 additions & 2 deletions ServiceLevelIndicators/tests/ServiceLevelIndicatorTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ public async Task Will_measure_code_block()
new("CustomerResourceId", customerResourceId),
new("LocationId", locationId),
new("Operation", "SleepWorker"),
new("activity.status_code", nameof(System.Diagnostics.ActivityStatusCode.Ok)),
new("activity.status.code", nameof(System.Diagnostics.ActivityStatusCode.Ok)),
];

ValidateMetrics(sleepTime, approx: 100);
Expand Down Expand Up @@ -152,7 +152,7 @@ public void Customize_instrument_name()
ValidateMetrics(elapsedTime, InstrumentName);
}

private void ValidateMetrics(int elapsedTime, string instrumentName = "LatencySLI", int? approx = null)
private void ValidateMetrics(int elapsedTime, string instrumentName = "ServiceLevelIndicator", int? approx = null)
{
_callbackCalled.Should().BeTrue();
_actualTags.Should().BeEquivalentTo(_expectedTags);
Expand Down
10 changes: 10 additions & 0 deletions sample/GenerateSli/GenerateSli.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

</Project>
41 changes: 41 additions & 0 deletions sample/GenerateSli/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@

Console.WriteLine("Generating SLI started.");
var t1 = ClientRequests();
var t2 = ClientRequests();
var t3 = ClientRequests();
await Task.WhenAll(t1, t2, t3);
Console.WriteLine("Generating SLI done.");

static async Task ClientRequests()
{
string[] apiUrl = [
"https://localhost:63936/hello-world?api-version=2023-08-06",
"https://localhost:63936/hello-world/xavier?api-version=2023-08-06",
"https://localhost:63936/hello-world/micheal?api-version=2023-08-06",
"https://localhost:63936/hello-world/xavier?api-version=1996-06-06",
"https://localhost:63936/hello-world/micheal?api-version=1996-06-06",
];

Random rnd = new Random();
using var httpClient = new HttpClient();
for (var i = 1; i <= 200; i++)
{
try
{
await Task.Delay(rnd.Next(500, 3000));
var response = await httpClient.GetAsync(apiUrl[rnd.Next(apiUrl.Length)]);

if (response.IsSuccessStatusCode)
await response.Content.ReadAsStringAsync();
else
Console.WriteLine($"Request {i}: Failed with status code {response.StatusCode}");
}
catch (Exception ex)
{
Console.WriteLine($"Request {i}: Exception occurred: {ex.Message}");
}
}
}



Loading
Loading