Created
September 21, 2026 12:11
-
-
Save sunmeat/dee2230e960af9437b9de82ebdea27d5 to your computer and use it in GitHub Desktop.
логування у файл з використанням бібліотеки Serilog
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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<RequestLoggingMiddleware>(); | |
| using (var scope = app.Services.CreateScope()) | |
| { | |
| var seeder = scope.ServiceProvider.GetRequiredService<FirestoreSeeder>(); | |
| await seeder.SeedAsync(); | |
| } | |
| app.MapControllers(); | |
| app.Run(); | |
| } | |
| catch (Exception ex) | |
| { | |
| // Serilog: логуємо критичну помилку старту | |
| Log.Fatal(ex, "Application terminated unexpectedly"); | |
| } | |
| finally | |
| { | |
| // Serilog: коректно закриваємо логер (скидаємо буфери на диск) | |
| Log.CloseAndFlush(); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment