-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
5 changed files
with
206 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
66 changes: 66 additions & 0 deletions
66
src/DiscordTranslationBot/Telemetry/TelemetryExtensions.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,66 @@ | ||
using Microsoft.Extensions.Options; | ||
using OpenTelemetry.Exporter; | ||
using OpenTelemetry.Logs; | ||
using OpenTelemetry.Metrics; | ||
using OpenTelemetry.Resources; | ||
using OpenTelemetry.Trace; | ||
|
||
namespace DiscordTranslationBot.Telemetry; | ||
|
||
internal static class TelemetryExtensions | ||
{ | ||
public static void AddTelemetry(this WebApplicationBuilder builder) | ||
{ | ||
var section = builder.Configuration.GetSection(TelemetryOptions.SectionName); | ||
builder.Services.AddOptions<TelemetryOptions>().Bind(section).ValidateDataAnnotations().ValidateOnStart(); | ||
|
||
var options = section.Get<TelemetryOptions>(); | ||
if (options?.Enabled != true) | ||
{ | ||
return; | ||
} | ||
|
||
var headers = $"X-Seq-ApiKey={options.ApiKey}"; | ||
|
||
builder.Logging.AddOpenTelemetry( | ||
o => o.AddOtlpExporter( | ||
e => | ||
{ | ||
e.Protocol = OtlpExportProtocol.HttpProtobuf; | ||
e.Endpoint = options.LoggingEndpointUrl!; | ||
e.Headers = headers; | ||
})); | ||
|
||
builder | ||
.Services | ||
.AddOpenTelemetry() | ||
.ConfigureResource( | ||
b => b | ||
.AddService(builder.Environment.ApplicationName) | ||
.AddAttributes( | ||
new Dictionary<string, object> { ["environment"] = builder.Environment.EnvironmentName })) | ||
.WithMetrics(b => b.AddAspNetCoreInstrumentation().AddHttpClientInstrumentation().AddPrometheusExporter()) | ||
.WithTracing( | ||
b => b | ||
.AddAspNetCoreInstrumentation() | ||
.AddHttpClientInstrumentation() | ||
.AddOtlpExporter( | ||
e => | ||
{ | ||
e.Protocol = OtlpExportProtocol.HttpProtobuf; | ||
e.Endpoint = options.TracingEndpointUrl!; | ||
e.Headers = headers; | ||
})); | ||
} | ||
|
||
public static void UseTelemetry(this WebApplication app) | ||
{ | ||
var options = app.Services.GetRequiredService<IOptions<TelemetryOptions>>(); | ||
if (!options.Value.Enabled) | ||
{ | ||
return; | ||
} | ||
|
||
app.MapPrometheusScrapingEndpoint("/_metrics"); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
using System.ComponentModel.DataAnnotations; | ||
|
||
namespace DiscordTranslationBot.Telemetry; | ||
|
||
public sealed class TelemetryOptions : IValidatableObject | ||
{ | ||
/// <summary> | ||
/// Configuration section name for <see cref="TelemetryOptions" />. | ||
/// </summary> | ||
public const string SectionName = "Telemetry"; | ||
|
||
/// <summary> | ||
/// Flag indicating whether telemetry is enabled. | ||
/// </summary> | ||
public bool Enabled { get; init; } | ||
|
||
/// <summary> | ||
/// The API key for Seq used by <see cref="LoggingEndpointUrl" /> and <see cref="TracingEndpointUrl" />. | ||
/// </summary> | ||
public string? ApiKey { get; init; } | ||
|
||
/// <summary> | ||
/// The URL for logging endpoint. | ||
/// </summary> | ||
public Uri? LoggingEndpointUrl { get; init; } | ||
|
||
/// <summary> | ||
/// The URL for tracing endpoint. | ||
/// </summary> | ||
public Uri? TracingEndpointUrl { get; init; } | ||
|
||
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) | ||
{ | ||
if (Enabled) | ||
{ | ||
if (string.IsNullOrWhiteSpace(ApiKey)) | ||
{ | ||
yield return new ValidationResult( | ||
$"{nameof(TelemetryOptions)}.{nameof(ApiKey)} is required.", | ||
[nameof(ApiKey)]); | ||
} | ||
|
||
if (LoggingEndpointUrl?.IsAbsoluteUri != true) | ||
{ | ||
yield return new ValidationResult( | ||
$"{nameof(TelemetryOptions)}.{nameof(LoggingEndpointUrl)} is must be an absolute URI.", | ||
[nameof(LoggingEndpointUrl)]); | ||
} | ||
|
||
if (TracingEndpointUrl?.IsAbsoluteUri != true) | ||
{ | ||
yield return new ValidationResult( | ||
$"{nameof(TelemetryOptions)}.{nameof(TracingEndpointUrl)} is must be an absolute URI.", | ||
[nameof(TracingEndpointUrl)]); | ||
} | ||
} | ||
} | ||
} |
68 changes: 68 additions & 0 deletions
68
tests/DiscordTranslationBot.Tests.Unit/Telemetry/TelemetryOptionsTests.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,68 @@ | ||
using DiscordTranslationBot.Extensions; | ||
using DiscordTranslationBot.Telemetry; | ||
|
||
namespace DiscordTranslationBot.Tests.Unit.Telemetry; | ||
|
||
public sealed class TelemetryOptionsTests | ||
{ | ||
[Theory] | ||
[InlineData(false)] | ||
[InlineData(true)] | ||
public void Valid_Options_ValidatesWithoutErrors(bool enabled) | ||
{ | ||
// Arrange | ||
var options = enabled | ||
? new TelemetryOptions | ||
{ | ||
Enabled = true, | ||
ApiKey = "apikey", | ||
LoggingEndpointUrl = new Uri("http://localhost:1234"), | ||
TracingEndpointUrl = new Uri("http://localhost:1234") | ||
} | ||
: new TelemetryOptions(); | ||
|
||
// Act | ||
var isValid = options.TryValidate(out var validationResults); | ||
|
||
// Assert | ||
isValid.Should().BeTrue(); | ||
validationResults.Should().BeEmpty(); | ||
} | ||
|
||
[Theory] | ||
[InlineData(null)] | ||
[InlineData("")] | ||
[InlineData(" ")] | ||
public void Invalid_Options_HasValidationErrors(string? stringValue) | ||
{ | ||
// Arrange | ||
var options = new TelemetryOptions | ||
{ | ||
Enabled = true, | ||
ApiKey = stringValue, | ||
LoggingEndpointUrl = null, | ||
TracingEndpointUrl = null | ||
}; | ||
|
||
// Act | ||
var isValid = options.TryValidate(out var validationResults); | ||
|
||
// Assert | ||
isValid.Should().BeFalse(); | ||
|
||
validationResults | ||
.Should() | ||
.HaveCount(3) | ||
.And | ||
.ContainSingle( | ||
x => x.ErrorMessage!.Contains($"{nameof(TelemetryOptions)}.{nameof(TelemetryOptions.ApiKey)}")) | ||
.And | ||
.ContainSingle( | ||
x => x.ErrorMessage!.Contains( | ||
$"{nameof(TelemetryOptions)}.{nameof(TelemetryOptions.LoggingEndpointUrl)}")) | ||
.And | ||
.ContainSingle( | ||
x => x.ErrorMessage!.Contains( | ||
$"{nameof(TelemetryOptions)}.{nameof(TelemetryOptions.TracingEndpointUrl)}")); | ||
} | ||
} |