логування у файл з використанням бібліотеки Serilog
翻译
| // dotnet add Soccer.WebAPI package Serilog.AspNetCore | |
| // dotnet add Soccer.WebAPI package Serilog.Sinks.File | |
| // dotnet add Soccer.WebAPI package Serilog.Formatting.Compact # для JSON | |
| // папка з логами буде в Soccer.WebAPI/logs/ | |
| // не забудьте додати в .gitignore: text**/logs/ | |
| using Soccer.Application.DependencyInjection; | |
| using Soccer.Infrastructure.DependencyInjection; | |
| using Soccer.Infrastructure.Persistence; | |
| using Soccer.WebAPI.Middleware; | |
| using Serilog; | |
| // Serilog: створюємо логер до побудови host, | |
| // щоб навіть помилки старту потрапляли в логи | |
| Log.Logger = new LoggerConfiguration() | |
| .MinimumLevel.Information() | |
| .MinimumLevel.Override("Microsoft.AspNetCore", Serilog.Events.LogEventLevel.Warning) | |
| .MinimumLevel.Override("Microsoft.Hosting.Lifetime", Serilog.Events.LogEventLevel.Information) | |
| .Enrich.FromLogContext() | |
| .WriteTo.Console() // термінал | |
| .WriteTo.File( // файл з ротацією | |
| path: "logs/log-.txt", | |
| rollingInterval: RollingInterval.Day, | |
| retainedFileCountLimit: 14, | |
| outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}") | |
| .CreateLogger(); | |
| try | |
| { | |
| var builder = WebApplication.CreateBuilder(args); | |
| // Serilog: підміняємо стандартні провайдери логування | |
| builder.Host.UseSerilog(); | |
| string firebasePath = Path.GetFullPath( | |
| Path.Combine( | |
| builder.Environment.ContentRootPath, | |
| "..", | |
| "Soccer.Infrastructure", | |
| "firebase.json")); | |
| builder.Services.AddInfrastructure(firebasePath); | |
| builder.Services.AddApplication(); | |
| builder.Services.AddControllers(); | |
| var app = builder.Build(); | |
| // Serilog: компактне HTTP-логування запитів (метод, path, status, duration) | |
| app.UseSerilogRequestLogging(); | |
| app.UseMiddleware(); | |
| using (var scope = app.Services.CreateScope()) | |
| { | |
| var seeder = scope.ServiceProvider.GetRequiredService(); | |
| await seeder.SeedAsync(); | |
| } | |
| app.MapControllers(); | |
| app.Run(); | |
| } | |
| catch (Exception ex) | |
| { | |
| // Serilog: логуємо критичну помилку старту | |
| Log.Fatal(ex, "Application terminated unexpectedly"); | |
| } | |
| finally | |
| { | |
| // Serilog: коректно закриваємо логер (скидаємо буфери на диск) | |
| Log.CloseAndFlush(); | |
| } |
评论
?
参与讨论