From f4eb7178d6d26926c18d2d5bdf4caf4fc009bf44 Mon Sep 17 00:00:00 2001 From: patthehyruler Date: Sat, 28 Sep 2024 12:44:53 +0300 Subject: [PATCH] Include app crash error in serilog logs --- WebApp/Program.cs | 141 ++++++++++++++++++++++++++-------------------- 1 file changed, 80 insertions(+), 61 deletions(-) diff --git a/WebApp/Program.cs b/WebApp/Program.cs index dc74de9..ef184a0 100644 --- a/WebApp/Program.cs +++ b/WebApp/Program.cs @@ -122,89 +122,108 @@ // Configure the HTTP request pipeline. -if (!app.Environment.IsDevelopment() || true) +try { - await using var scope = app.Services.CreateAsyncScope(); - await scope.ServiceProvider.MigrateDbAsync(); -} + if (!app.Environment.IsDevelopment() || true) + { + await using var scope = app.Services.CreateAsyncScope(); + await scope.ServiceProvider.MigrateDbAsync(); + } -app.SeedIdentity(); -app.SetupYouTube(); + app.SeedIdentity(); + app.SetupYouTube(); -app.UseHttpsRedirection(); + app.UseHttpsRedirection(); -app.UseWhen(context => context.Request.Path.StartsWithSegments("/api"), apiApp => -{ - apiApp.UseExceptionHandler(apiBuilder => + app.UseWhen(context => context.Request.Path.StartsWithSegments("/api"), apiApp => { - apiBuilder.Run(async context => + apiApp.UseExceptionHandler(apiBuilder => { - context.Response.StatusCode = StatusCodes.Status500InternalServerError; - await context.Response.WriteAsJsonAsync(new ErrorResponseDto + apiBuilder.Run(async context => { - ErrorType = EErrorType.GenericError, - Message = "Something went wrong", - }, JsonUtils.DefaultJsonSerializerOptions); + context.Response.StatusCode = StatusCodes.Status500InternalServerError; + await context.Response.WriteAsJsonAsync(new ErrorResponseDto + { + ErrorType = EErrorType.GenericError, + Message = "Something went wrong", + }, JsonUtils.DefaultJsonSerializerOptions); + }); }); }); -}); -if (app.Environment.IsDevelopment()) -{ - app.UseSwagger(); - app.UseSwaggerUI(options => + if (app.Environment.IsDevelopment()) { - var provider = app.Services.GetRequiredService(); - foreach (var description in provider.ApiVersionDescriptions) + app.UseSwagger(); + app.UseSwaggerUI(options => { - options.SwaggerEndpoint($"/swagger/{description.GroupName}/swagger.json", description.GroupName); - } + var provider = app.Services.GetRequiredService(); + foreach (var description in provider.ApiVersionDescriptions) + { + options.SwaggerEndpoint($"/swagger/{description.GroupName}/swagger.json", description.GroupName); + } + }); + } + + var imagesDirectory = app.Services.GetRequiredService().GetImagesDirectoryAbsolute(); + var imagesDirectoryPath = Path.Combine(app.Environment.ContentRootPath, imagesDirectory); + Directory.CreateDirectory(imagesDirectoryPath); + app.UseStaticFiles(new StaticFileOptions + { + FileProvider = new PhysicalFileProvider(imagesDirectoryPath), + RequestPath = "/images", }); -} -var imagesDirectory = app.Services.GetRequiredService().GetImagesDirectoryAbsolute(); -var imagesDirectoryPath = Path.Combine(app.Environment.ContentRootPath, imagesDirectory); -Directory.CreateDirectory(imagesDirectoryPath); -app.UseStaticFiles(new StaticFileOptions -{ - FileProvider = new PhysicalFileProvider(imagesDirectoryPath), - RequestPath = "/images", -}); + app.UseStaticFiles(); -app.UseStaticFiles(); + string[] specialPaths = ["/api", "/hangfire"]; + bool IsSpecialPath(string path) => specialPaths.Any(path.StartsWith); -string[] specialPaths = ["/api", "/hangfire"]; -bool IsSpecialPath(string path) => specialPaths.Any(path.StartsWith); + var spaIndexPath = Path.Combine(app.Environment.ContentRootPath, spaDirectory, "index.html"); + if (Path.Exists(spaIndexPath)) + { + app.MapWhen(c => !IsSpecialPath(c.Request.Path.Value ?? ""), + spaAppBuilder => + { + spaAppBuilder.UseSpaStaticFiles(); + spaAppBuilder.UseSpa(_ => { }); + }); + } -var spaIndexPath = Path.Combine(app.Environment.ContentRootPath, spaDirectory, "index.html"); -if (Path.Exists(spaIndexPath)) -{ - app.MapWhen(c => !IsSpecialPath(c.Request.Path.Value ?? ""), - spaAppBuilder => - { - spaAppBuilder.UseSpaStaticFiles(); - spaAppBuilder.UseSpa(_ => { }); - }); -} + app.UseRouting(); -app.UseRouting(); + app.UseCors(corsAllowAllName); + app.UseCors(corsAllowCredentialsName); -app.UseCors(corsAllowAllName); -app.UseCors(corsAllowCredentialsName); + app.UseAuthentication(); + app.UseAuthorization(); -app.UseAuthentication(); -app.UseAuthorization(); + app.UseHangfireDashboard(options: new DashboardOptions + { + AppPath = null, + DarkModeEnabled = true, + Authorization = app.Services.GetRequiredService>(), + AsyncAuthorization = app.Services.GetRequiredService>(), + }); -app.UseHangfireDashboard(options: new DashboardOptions -{ - AppPath = null, - DarkModeEnabled = true, - Authorization = app.Services.GetRequiredService>(), - AsyncAuthorization = app.Services.GetRequiredService>(), -}); + app.MapControllers(); -app.MapControllers(); + app.Run(); +} +catch (Exception e) +{ + try + { + await using var scope = app.Services.CreateAsyncScope(); + var logger = scope.ServiceProvider.GetRequiredService>(); + logger.LogError(e, "An error occured while running the application."); + await Log.CloseAndFlushAsync(); + } + catch (Exception logException) + { + await Console.Error.WriteLineAsync($"Failed to log catchall application error {logException.GetType()}: {logException.Message}"); + } + throw; +} -app.Run(); return; string GetHangfireConnectionString(WebApplicationBuilder webApplicationBuilder)