Otel.Simplify 1.0.0

dotnet add package Otel.Simplify --version 1.0.0
                    
NuGet\Install-Package Otel.Simplify -Version 1.0.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Otel.Simplify" Version="1.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Otel.Simplify" Version="1.0.0" />
                    
Directory.Packages.props
<PackageReference Include="Otel.Simplify" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Otel.Simplify --version 1.0.0
                    
#r "nuget: Otel.Simplify, 1.0.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#addin nuget:?package=Otel.Simplify&version=1.0.0
                    
Install Otel.Simplify as a Cake Addin
#tool nuget:?package=Otel.Simplify&version=1.0.0
                    
Install Otel.Simplify as a Cake Tool

📦 OpenTelemetry.Simplify — Библиотека для упрощения и стандартизации работы с OpenTelemetry в .NET

⚠️ Внимание: Этот пакет не является официальным компонентом проекта OpenTelemetry. Это сторонняя обёртка, созданная для упрощения интеграции OpenTelemetry в .NET-приложениях.

OpenTelemetry.Simplify — это NuGet-библиотека, предназначенная для стандартизации и упрощения подключения OpenTelemetry к .NET приложениям. Она предоставляет полную интеграцию метрик и трассировок с Prometheus, OTLP, Jaeger, поддерживает регистрацию кастомных метрик, автоматическое подключение Meter, а также готовые Grafana дешборды.


🔧 Возможности библиотеки

  • 📊 Интеграция системных метрик: ASP.NET Core, Runtime, Uptime, Oracle (опционально)
  • ⚙️ Поддержка кастомных метрик через интерфейс ICustomMetric
  • 🔍 Поддержка трассировки: входящие и исходящие HTTP-запросы
  • 🌐 Поддержка экспортёров: Prometheus, OTLP, Jaeger, Console
  • 🧩 Автоматическая регистрация Meter через IMeterAccessor
  • 🚀 Extension-методы для удобной регистрации метрик и трейсов

📦 Установка

dotnet add package OpenTelemetry.Simplify

<PackageReference Include="OpenTelemetry.Simplify" Version="1.0.0" />

🚀 Быстрый старт

builder.Services.AddOpenTelemetrySimplify(options =>
{
    options.ServiceName = "MyService";
    options.ServiceVersion = "1.0.0";

    options.AddMetrics(metrics =>
    {
        metrics.UseAspNetCoreInstrumentation();
        metrics.UseRuntimeInstrumentation();
        metrics.UseUptime();
        metrics.UseExporter(MetricExporterType.Prometheus);
    });

    options.AddTrace(tracing =>
    {
        tracing.UseAspNetCoreInstrumentation();
        tracing.UseHttpClientInstrumentation();
        tracing.UseExporter(TraceExporterType.Jaeger);
    });
});

var app = builder.Build();
app.UseOpenTelemetryPrometheusScrapingEndpoint();

📊 Встроенные метрики

ASP.NET Core

  • Количество запросов
  • Время выполнения (latency)
  • Активные запросы
  • Коды ответов

Runtime

  • Память
  • GC
  • Исключения
  • Потоки и аллокации

Uptime

  • Время непрерывной работы приложения (в секундах)

Oracle (опционально)

  • Метрики пула соединений и времени выполнения команд (требует Oracle.ManagedDataAccess.Core 23.3.2+)

🧠 Кастомные метрики через ICustomMetric

Пример без зависимостей

public class SampleCustomMetric : ICustomMetric
{
    private readonly DateTimeOffset _startTime = DateTimeOffset.UtcNow;

    public void Register(Meter meter)
    {
        meter.CreateObservableGauge<double>(
            name: "test_uptime_seconds_test",
            observeValues: () =>
            {
                double uptime = (DateTimeOffset.UtcNow - _startTime).TotalSeconds;
                return new[] { new Measurement<double>(uptime) };
            },
            unit: "seconds",
            description: "Description");
    }
}

Пример с зависимостью

public class RandomCustomMetric : ICustomMetric
{
    private readonly IRandomService _service;
    public RandomCustomMetric(IRandomService service) => _service = service;

    public void Register(Meter meter)
    {
        meter.CreateObservableGauge("random_number",
            () => new Measurement<int>(_service.GetRandomNumber()));
    }
}

Регистрация:

builder.Services.AddOpenTelemetrySimplify(options =>
{
    options.AddMetrics(metrics =>
    {
        metrics.AddCustomMetric<SampleCustomMetric>();
    });
});

app.RegisterCustomMetrics(
    new RandomCustomMetric(app.Services.GetRequiredService<IRandomService>())
);

🔧 IMeterAccessor — правильный способ получить Meter

public interface IMeterAccessor
{
    Meter Meter { get; }
}
var meter = app.Services.GetRequiredService<IMeterAccessor>().Meter;

⚙️ Использование Meter напрямую в middleware или HostedService

public class MetricsMiddleware
{
    private readonly RequestDelegate _next;
    private readonly Counter<long> _counter;

    public MetricsMiddleware(RequestDelegate next, IMeterAccessor meterAccessor)
    {
        _next = next;
        _counter = meterAccessor.Meter.CreateCounter<long>("custom_middleware_requests_total", "req", "Запросы через middleware");
    }

    public async Task InvokeAsync(HttpContext context)
    {
        _counter.Add(1);
        await _next(context);
    }
}
app.UseMiddleware<MetricsMiddleware>();

📊 Grafana Dashboards

(в процессе подготовки)


📁 Структура библиотеки

Путь Назначение
TelemetryConfigurator.cs Конфигурация метрик и трейсов
TelemetryOptions.cs Корневая конфигурация
MetricsOptions.cs Опции метрик и экспортёров
TracingOptions.cs Опции трассировки
ICustomMetric.cs Интерфейс для кастомной метрики
IMeterAccessor.cs Интерфейс доступа к Meter
MeterAccessor.cs Реализация IMeterAccessor
TelemetryAppExtensions.cs Extension-методы для регистрации после Build
UptimeMetric.cs Метрика аптайма

✅ Рекомендации по использованию

ℹ️ Важно: если вы используете метрики, зависящие от сервисов через Dependency Injection (DI), обязательно регистрируйте их через app.RegisterCustomMetrics(...) после app.Build().

  • Не используй new Meter(...) — только IMeterAccessor
  • Всегда указывай ServiceName и ServiceVersion
  • Метрики с зависимостями регистрируй после app.Build()
  • Даём meaningful-названия метрикам (например: my_service.http_duration_seconds)

🗂 Структура проекта

OpenTelemetry.Simplify/
├── src/
│   └── OpenTelemetry.Simplify/
├── examples/
│   └── OpenTelemetry.Simplify.Example/ (Web API)
└── OpenTelemetry.Simplify.sln

📝 Лицензия

MIT © 2025 — OpenTelemetry.Simplify Contributors

Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
1.0.0 160 4/30/2025