Added dependency injection

This commit is contained in:
2026-06-02 19:09:35 +02:00
parent dd6aa547f9
commit 3cb5ee52a0
8 changed files with 1022 additions and 12 deletions
+335 -1
View File
@@ -474,4 +474,338 @@ server.LogDropped += line => Metrics.Increment("dropped");
Console.CancelKeyPress += (_, e) => { e.Cancel = true; server.Stop(); };
```
`Stop()` prints a throughput summary and disposes all listeners cleanly.
`Stop()` prints a throughput summary and disposes all listeners cleanly.
## Dependency Injection (DI) registration methods
### 1. Basic Registration (Simplest)
Register with default settings:
```csharp
services.AddEonaCatLogging();
```
This registers:
- `ILoggerFactory` - For creating category-specific loggers
- `Microsoft.Extensions.Logging.ILoggerFactory` - For Microsoft.Extensions.Logging compatibility
- `ILogger` - For injecting the default logger
### 2. Registration with Log Level and Timestamp Mode
```csharp
services.AddEonaCatLogging(
minimumLevel: LogLevel.Information,
timestampMode: TimestampMode.Local);
```
### 3. Registration with Pre-built EonaCatLogStack
If you've already created an `EonaCatLogStack` instance:
```csharp
var logStack = new EonaCatLogStack("MyApp");
logStack.AddFlow(new ConsoleFlow());
services.AddEonaCatLogging(logStack);
```
### 4. Registration with Configuration Callback (Recommended)
Configure the logger directly with an `Action<EonaCatLogStack>`:
```csharp
services.AddEonaCatLogging(logStack =>
{
logStack.AddFlow(new ConsoleFlow());
logStack.AddFlow(new FileFlow("./logs"));
logStack.AddBooster(new MachineNameBooster());
});
```
### 5. Registration with LogBuilder (Most Fluent - Recommended)
Use the fluent `LogBuilder` API for the most intuitive configuration:
```csharp
services.AddEonaCatLogging("MyApplication", builder =>
{
builder
.WithMinimumLevel(LogLevel.Information)
.WithTimestampMode(TimestampMode.Local)
.WriteToConsole()
.WriteToFile("./logs")
.BoostWithMachineName()
.BoostWithProcessId()
.BoostWithCorrelationId();
});
```
Or with the default "Application" category:
```csharp
services.AddEonaCatLogging(builder =>
{
builder
.WriteToConsole()
.WriteToFile("./logs");
});
```
### 6. Registration with Factory Method (Advanced)
For advanced scenarios where you need access to the service provider:
```csharp
services.AddEonaCatLoggingFactory("MyApplication", builder =>
{
builder
.WriteToConsole()
.WriteToFile("./logs");
});
```
## Using in Your Application
### Injecting ILoggerFactory
```csharp
public class MyService
{
private readonly ILoggerFactory _loggerFactory;
public MyService(ILoggerFactory loggerFactory)
{
_loggerFactory = loggerFactory;
}
public void DoSomething()
{
var logger = _loggerFactory.CreateLogger("MyService");
logger.Log(LogLevel.Information, "Doing something");
}
}
```
### Injecting ILogger
```csharp
public class MyService
{
private readonly ILogger _logger;
public MyService(ILogger logger)
{
_logger = logger;
}
public void DoSomething()
{
_logger.Log(LogLevel.Information, "Doing something");
}
}
```
### Using with Microsoft.Extensions.Logging.ILogger
```csharp
public class MyService
{
private readonly Microsoft.Extensions.Logging.ILogger _logger;
public MyService(Microsoft.Extensions.Logging.ILogger logger)
{
_logger = logger;
}
public void DoSomething()
{
_logger.LogInformation("Doing something");
}
}
```
## ASP.NET Core / Razor Pages Integration
In your `Program.cs`:
```csharp
var builder = WebApplication.CreateBuilder(args);
// Add EonaCat LogStack to the service collection
builder.Services.AddEonaCatLogging("WebApplication", logBuilder =>
{
logBuilder
.WithMinimumLevel(LogLevel.Information)
.WriteToConsole(useColors: true)
.WriteToFile("./logs")
.BoostWithCorrelationId()
.BoostWithThreadId();
});
// Rest of your configuration...
var app = builder.Build();
// Configure HTTP request pipeline...
app.Run();
```
### In Razor Page Code-Behind
```csharp
public class IndexModel : PageModel
{
private readonly ILogger _logger;
public IndexModel(ILogger logger)
{
_logger = logger;
}
public void OnGet()
{
_logger.Log(LogLevel.Information, "Index page loaded");
}
}
```
## Features
### Multiple Output Destinations (Flows)
```csharp
services.AddEonaCatLogging(builder =>
{
builder
.WriteToConsole() // Console output
.WriteToFile("./logs") // File output
.WriteToSlack("https://hooks.slack.com/...") // Slack
.WriteToDiscord("https://discordapp.com/...") // Discord
.WriteToElasticSearch("http://localhost:9200") // Elasticsearch
.WriteToEmail("smtp.gmail.com", 587, ...) // Email
.WriteToMicrosoftTeams("https://..."); // Teams
});
```
### Enriching Log Events (Boosters)
```csharp
services.AddEonaCatLogging(builder =>
{
builder
.BoostWithMachineName() // Adds machine name
.BoostWithProcessId() // Adds process ID
.BoostWithThreadId() // Adds thread ID
.BoostWithCorrelationId() // Adds correlation ID (for distributed tracing)
.BoostWithMemory() // Adds memory usage
.BoostWithOS() // Adds OS info
.BoostWithUser() // Adds username
.BoostWithCustomText("Environment", "Production"); // Custom properties
});
```
### Log Level Filtering
```csharp
services.AddEonaCatLogging(builder =>
{
builder
.WithMinimumLevel(LogLevel.Warning) // Only log warnings and above
.WriteToConsole(minimumLevel: LogLevel.Information) // More verbose for console
.WriteToFile("./logs", minimumLevel: LogLevel.Error); // Only errors to file
});
```
## Best Practices
1. **Use LogBuilder for Configuration**: The fluent LogBuilder API is the most readable and maintainable approach.
2. **Register Early**: Register logging in `Program.cs` before other services that depend on logging.
3. **Use Appropriate Log Levels**:
- `Trace` - Very detailed diagnostic info
- `Debug` - Debug-level diagnostic info
- `Information` - General informational messages
- `Warning` - Warning messages
- `Error` - Error messages
- `Critical` - Critical failures
4. **Inject Specific Types**: Prefer injecting `ILoggerFactory` to create category-specific loggers rather than injecting a single shared logger.
5. **Use Categories**: Create loggers with meaningful category names:
```csharp
var logger = loggerFactory.CreateLogger("MyApp.Services.UserService");
```
6. **Enable Correlation IDs**: For distributed tracing scenarios:
```csharp
builder.BoostWithCorrelationId()
```
## Configuration Examples
### Minimal Setup (Console Only)
```csharp
services.AddEonaCatLogging(b => b.WriteToConsole());
```
### Development Environment
```csharp
services.AddEonaCatLogging(builder =>
{
builder
.WithMinimumLevel(LogLevel.Debug)
.WriteToConsole(useColors: true)
.WriteToFile("./logs")
.BoostWithMachineName()
.BoostWithThreadId();
});
```
### Production Environment
```csharp
services.AddEonaCatLogging("ProductionApp", builder =>
{
builder
.WithMinimumLevel(LogLevel.Information)
.WriteToFile("./logs", minimumLevel: LogLevel.Information)
.WriteToElasticSearch("https://elastic.company.com")
.WriteToSlack("https://hooks.slack.com/...")
.BoostWithCorrelationId()
.BoostWithMachineName()
.BoostWithUser();
});
```
## Diagnostics
```csharp
public class DiagnosticsService
{
private readonly ILoggerFactory _loggerFactory;
public DiagnosticsService(ILoggerFactory loggerFactory)
{
_loggerFactory = loggerFactory;
}
public void PrintDiagnostics()
{
var diagnostics = _loggerFactory.GetDiagnostics();
Console.WriteLine($"Total Logged: {diagnostics.TotalLoggedCount}");
Console.WriteLine($"Total Dropped: {diagnostics.TotalDroppedCount}");
}
}
```
## Disposing of the Logger
The logger is registered as a Singleton in the DI container, so it will be automatically disposed when the application shuts down. You can also manually access and dispose it:
```csharp
var loggerFactory = app.Services.GetRequiredService<ILoggerFactory>();
await loggerFactory.DisposeAsync();
```