Examples
ASP.NET Core and console logging examples with Oleq.Ai.Logs
| Stack | Where to init | When to flush |
|---|---|---|
| ASP.NET Core | Program.cs singleton | IHostApplicationLifetime shutdown |
| Console / worker | Main | finally / Ctrl+C handler |
ASP.NET Core
Register OleqLog as a singleton and flush on shutdown:
using Oleq.Ai.Logs;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton(_ => new OleqLog(new LoggerConfig
{
AppName = "api",
Environment = builder.Environment.EnvironmentName,
}));
var app = builder.Build();
var lifetime = app.Services.GetRequiredService<IHostApplicationLifetime>();
lifetime.ApplicationStopping.Register(() =>
{
var log = app.Services.GetRequiredService<OleqLog>();
log.FlushAsync().GetAwaiter().GetResult();
log.DisposeAsync().AsTask().GetAwaiter().GetResult();
});
app.MapGet("/health", async (OleqLog log) =>
{
await log.InfoAsync(new LogPayload { Message = "health check" });
await log.FlushAsync();
return Results.Ok();
});
app.Run();Request middleware
public sealed class RequestLoggingMiddleware
{
private readonly RequestDelegate _next;
private readonly OleqLog _log;
public RequestLoggingMiddleware(RequestDelegate next, OleqLog log)
{
_next = next;
_log = log;
}
public async Task InvokeAsync(HttpContext ctx)
{
var sw = System.Diagnostics.Stopwatch.StartNew();
await _next(ctx);
sw.Stop();
await _log.InfoAsync(new LogPayload
{
Message = $"{ctx.Request.Method} {ctx.Request.Path} {ctx.Response.StatusCode}",
Kind = LogKind.Res,
Body = new { ms = sw.ElapsedMilliseconds, status = ctx.Response.StatusCode },
});
}
}Console / worker
using Oleq.Ai.Logs;
await using var log = new OleqLog(new LoggerConfig { AppName = "worker" });
Console.CancelKeyPress += async (_, e) =>
{
e.Cancel = true;
await log.FlushAsync();
Environment.Exit(0);
};
await log.InfoAsync(new LogPayload { Message = "job started" });
// … work …
await log.FlushAsync();Back: Usage