JonjubNet.Metrics
1.0.3
dotnet add package JonjubNet.Metrics --version 1.0.3
NuGet\Install-Package JonjubNet.Metrics -Version 1.0.3
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="JonjubNet.Metrics" Version="1.0.3" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="JonjubNet.Metrics" Version="1.0.3" />
<PackageReference Include="JonjubNet.Metrics" />
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 JonjubNet.Metrics --version 1.0.3
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
#r "nuget: JonjubNet.Metrics, 1.0.3"
#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.
#:package JonjubNet.Metrics@1.0.3
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=JonjubNet.Metrics&version=1.0.3
#tool nuget:?package=JonjubNet.Metrics&version=1.0.3
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
JonjubNet.Metrics
Biblioteca de métricas para aplicaciones .NET con soporte para contadores, gauges, histogramas y timers, integración con Prometheus y exportación a múltiples formatos.
🚀 Características
- Métricas Estándar: Soporte completo para contadores, gauges, histogramas y timers
- Integración Prometheus: Exportación nativa a formato Prometheus
- Middleware HTTP: Captura automática de métricas HTTP
- Métricas de Base de Datos: Tracking automático de operaciones de BD
- Métricas de Negocio: Soporte para métricas personalizadas de negocio
- Configuración Flexible: Configuración completa via appsettings.json
- Etiquetas Dinámicas: Soporte para etiquetas personalizadas
- Alto Rendimiento: Basado en Prometheus.Client para máximo rendimiento
- .NET 10.0: Compatible con las últimas versiones de .NET
📦 Instalación
dotnet add package JonjubNet.Metrics
🔧 Configuración
1. Configurar en Program.cs
using JonjubNet.Metrics;
var builder = WebApplication.CreateBuilder(args);
// Agregar servicios
builder.Services.AddMetricsInfrastructure(builder.Configuration);
var app = builder.Build();
// Usar middleware de métricas HTTP
app.UseMetricsMiddleware();
// Configurar endpoint de Prometheus
app.UsePrometheusServer();
app.Run();
2. Configurar en appsettings.json
{
"Metrics": {
"Enabled": true,
"ServiceName": "MiAplicacion",
"Environment": "Development",
"Counter": {
"Enabled": true,
"DefaultIncrement": 1,
"EnableLabels": true
},
"Gauge": {
"Enabled": true,
"EnableLabels": true
},
"Histogram": {
"Enabled": true,
"DefaultBuckets": [0.1, 0.5, 1.0, 2.5, 5.0, 10.0],
"EnableLabels": true
},
"Timer": {
"Enabled": true,
"DefaultBuckets": [0.1, 0.5, 1.0, 2.5, 5.0, 10.0],
"EnableLabels": true
},
"Export": {
"Enabled": true,
"ExportIntervalSeconds": 30,
"Formats": ["Prometheus", "JSON"],
"Prometheus": {
"Enabled": true,
"Endpoint": "/metrics",
"Port": 9090
}
},
"Middleware": {
"Enabled": true,
"HttpMetrics": {
"Enabled": true,
"TrackRequestDuration": true,
"TrackRequestSize": true,
"TrackResponseSize": true,
"TrackStatusCode": true,
"ExcludePaths": ["/health", "/metrics", "/swagger"]
}
}
}
}
📊 Uso
Métricas Básicas
public class MiServicio
{
private readonly IMetricsService _metricsService;
public MiServicio(IMetricsService metricsService)
{
_metricsService = metricsService;
}
public async Task ProcesarDatos()
{
// Contador
await _metricsService.RecordCounterAsync("datos_procesados", 1,
new Dictionary<string, string> { ["tipo"] = "importante" });
// Gauge
await _metricsService.RecordGaugeAsync("memoria_utilizada", 1024.5,
new Dictionary<string, string> { ["unidad"] = "MB" });
// Histograma
await _metricsService.RecordHistogramAsync("tiempo_procesamiento", 150.2,
new Dictionary<string, string> { ["operacion"] = "transformacion" });
// Timer
var stopwatch = Stopwatch.StartNew();
// ... operación ...
stopwatch.Stop();
await _metricsService.RecordTimerAsync("operacion_completa", stopwatch.Elapsed.TotalMilliseconds);
}
}
Métricas HTTP Automáticas
El middleware captura automáticamente:
- Duración de requests
- Códigos de estado HTTP
- Tamaño de requests y responses
- Método HTTP y endpoint
Métricas de Base de Datos
public async Task ConsultarUsuarios()
{
var stopwatch = Stopwatch.StartNew();
try
{
var usuarios = await _dbContext.Usuarios.ToListAsync();
stopwatch.Stop();
await _metricsService.RecordDatabaseMetricsAsync(new DatabaseMetrics
{
Operation = "SELECT",
Table = "Usuarios",
Database = "MiBaseDatos",
DurationMs = stopwatch.Elapsed.TotalMilliseconds,
RecordsAffected = usuarios.Count,
IsSuccess = true
});
return usuarios;
}
catch (Exception ex)
{
stopwatch.Stop();
await _metricsService.RecordDatabaseMetricsAsync(new DatabaseMetrics
{
Operation = "SELECT",
Table = "Usuarios",
Database = "MiBaseDatos",
DurationMs = stopwatch.Elapsed.TotalMilliseconds,
RecordsAffected = 0,
IsSuccess = false
});
throw;
}
}
Métricas de Negocio
public async Task ProcesarPedido(Pedido pedido)
{
var stopwatch = Stopwatch.StartNew();
try
{
// Procesar pedido...
stopwatch.Stop();
await _metricsService.RecordBusinessMetricsAsync(new BusinessMetrics
{
Operation = "ProcesarPedido",
MetricType = "Revenue",
Value = pedido.Total,
Category = "Ventas",
DurationMs = stopwatch.Elapsed.TotalMilliseconds,
IsSuccess = true,
Labels = new Dictionary<string, string>
{
["cliente_tipo"] = pedido.Cliente.Tipo,
["moneda"] = pedido.Moneda
}
});
}
catch (Exception ex)
{
stopwatch.Stop();
await _metricsService.RecordBusinessMetricsAsync(new BusinessMetrics
{
Operation = "ProcesarPedido",
MetricType = "Error",
Value = 1,
Category = "Errores",
DurationMs = stopwatch.Elapsed.TotalMilliseconds,
IsSuccess = false
});
throw;
}
}
🔍 Endpoints de Métricas
Prometheus
GET /metrics
JSON
GET /metrics/json
🏗️ Construcción
# Windows
.\build-package.ps1
# Linux/Mac
./build-package.sh
📈 Monitoreo
Grafana Dashboard
Ejemplo de consultas PromQL:
# Requests por segundo
rate(http_requests_total[5m])
# Latencia promedio
histogram_quantile(0.95, rate(http_request_duration_ms_bucket[5m]))
# Errores por minuto
rate(http_requests_total{status_code=~"5.."}[1m])
# Métricas de base de datos
rate(database_queries_total[5m])
🧪 Testing
[Test]
public async Task Debe_Registrar_Metrica_Correctamente()
{
// Arrange
var metricsService = new MetricsService(logger, options);
// Act
await metricsService.RecordCounterAsync("test_counter", 1);
// Assert
// Verificar que la métrica se registró correctamente
}
🤝 Contribuir
- Fork el proyecto
- Crea una rama para tu feature (
git checkout -b feature/AmazingFeature) - Commit tus cambios (
git commit -m 'Add some AmazingFeature') - Push a la rama (
git push origin feature/AmazingFeature) - Abre un Pull Request
📄 Licencia
Este proyecto está licenciado bajo la Licencia MIT - ver el archivo LICENSE para detalles.
🆘 Soporte
- 📧 Email: support@jonjubnet.com
- 🐛 Issues: GitHub Issues
- 📖 Documentación: Wiki
🔗 Enlaces Relacionados
- JonjubNet.Logging - Biblioteca de logging estructurado
- JonjubNet.Resilience - Biblioteca de resiliencia
- Prometheus - Sistema de monitoreo
- Grafana - Plataforma de visualización
Desarrollado con ❤️ por JonjubNet
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net10.0 is compatible. 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.
-
net10.0
- Microsoft.AspNetCore.Hosting.Abstractions (>= 2.2.0)
- Microsoft.AspNetCore.Http.Abstractions (>= 2.2.0)
- Microsoft.Extensions.Configuration.Abstractions (>= 9.0.0)
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 9.0.0)
- Microsoft.Extensions.Http (>= 9.0.0)
- Microsoft.Extensions.Logging.Abstractions (>= 9.0.0)
- Microsoft.Extensions.Options (>= 9.0.0)
- Microsoft.Extensions.Options.ConfigurationExtensions (>= 9.0.0)
- Prometheus.Client (>= 6.0.0)
- Prometheus.Client.AspNetCore (>= 6.0.0)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.