|
1 | 1 | using Microsoft.AspNetCore.Hosting; |
2 | 2 | using Microsoft.Extensions.Hosting; |
| 3 | +using Serilog; |
| 4 | +using Serilog.Enrichers.Span; |
3 | 5 |
|
4 | 6 | namespace ExamManagement.API |
5 | 7 | { |
6 | 8 | public class Program |
7 | 9 | { |
| 10 | + public static readonly string Namespace = typeof(Program).Namespace!; |
| 11 | + public static readonly string AppName = Namespace.Substring(Namespace.LastIndexOf('.', Namespace.LastIndexOf('.') - 1) + 1); |
| 12 | + |
| 13 | + [System.Diagnostics.CodeAnalysis.SuppressMessage( |
| 14 | + "Design", |
| 15 | + "CA1031:Do not catch general exception types", |
| 16 | + Justification = "Top level all exception catcher")] |
8 | 17 | public static void Main(string[] args) |
9 | 18 | { |
10 | | - CreateHostBuilder(args).Build().Run(); |
| 19 | + Activity.DefaultIdFormat = ActivityIdFormat.W3C; |
| 20 | + |
| 21 | + var configuration = GetConfiguration(); |
| 22 | + |
| 23 | + Log.Logger = CreateSerilogLogger(configuration); |
| 24 | + try |
| 25 | + { |
| 26 | + Log.Information("Configuring web host ({ApplicationContext})...", AppName); |
| 27 | + CreateHostBuilder(args).Build().Run(); |
| 28 | + |
| 29 | + return 0; |
| 30 | + } |
| 31 | + catch (Exception ex) |
| 32 | + { |
| 33 | + Log.Fatal(ex, "Host terminated unexpectedly"); |
| 34 | + return 1; |
| 35 | + } |
| 36 | + finally |
| 37 | + { |
| 38 | + Log.CloseAndFlush(); |
| 39 | + } |
11 | 40 | } |
12 | 41 |
|
13 | | - public static IHostBuilder CreateHostBuilder(string[] args) => |
| 42 | + public static IHostBuilder CreateHostBuilder(IConfiguration configuration,string[] args) => |
14 | 43 | Host.CreateDefaultBuilder(args) |
15 | 44 | .ConfigureWebHostDefaults(webBuilder => |
16 | 45 | { |
17 | 46 | webBuilder.UseStartup<Startup>(); |
| 47 | + webBuilder.UseConfiguration(configuration); |
| 48 | + webBuilder.UseSerilog(); |
18 | 49 | }); |
| 50 | + |
| 51 | + private static ILogger CreateSerilogLogger(IConfiguration configuration) |
| 52 | + { |
| 53 | + return new LoggerConfiguration() |
| 54 | + .MinimumLevel.Verbose() |
| 55 | + .Enrich.WithProperty("ApplicationContext", AppName) |
| 56 | + .Enrich.FromLogContext() |
| 57 | + .Enrich.WithSpan() |
| 58 | + .WriteTo.Console() |
| 59 | + .WriteTo.Seq("http://seq") |
| 60 | + .ReadFrom.Configuration(configuration) |
| 61 | + .CreateLogger(); |
| 62 | + } |
| 63 | + |
| 64 | + private static IConfiguration GetConfiguration() |
| 65 | + { |
| 66 | + var builder = new ConfigurationBuilder() |
| 67 | + .SetBasePath(Directory.GetCurrentDirectory()) |
| 68 | + .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) |
| 69 | + .AddEnvironmentVariables(); |
| 70 | + |
| 71 | + return builder.Build(); |
| 72 | + } |
19 | 73 | } |
20 | 74 | } |
0 commit comments