|
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 CertificateProcessing.API |
5 | 7 | { |
6 | 8 | public class Program |
7 | 9 | { |
8 | | - public static void Main(string[] args) |
| 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 | + public static int Main(string[] args) |
9 | 14 | { |
10 | | - CreateHostBuilder(args).Build().Run(); |
| 15 | + Activity.DefaultIdFormat = ActivityIdFormat.W3C; |
| 16 | + |
| 17 | + var configuration = GetConfiguration(); |
| 18 | + Log.Logger = CreateSerilogLogger(configuration); |
| 19 | + |
| 20 | + try |
| 21 | + { |
| 22 | + Log.Information("Configuring web host ({ApplicationContext})...", AppName); |
| 23 | + var host = CreateHostBuilder(configuration, args).Build(); |
| 24 | + |
| 25 | + Log.Information("Starting web host ({ApplicationContext})...", AppName); |
| 26 | + host.Run(); |
| 27 | + |
| 28 | + return 0; |
| 29 | + } |
| 30 | + catch (Exception ex) |
| 31 | + { |
| 32 | + Log.Fatal(ex, "Host terminated unexpectedly"); |
| 33 | + return 1; |
| 34 | + } |
| 35 | + finally |
| 36 | + { |
| 37 | + Log.CloseAndFlush(); |
| 38 | + } |
11 | 39 | } |
12 | 40 |
|
13 | | - public static IHostBuilder CreateHostBuilder(string[] args) => |
| 41 | + public static IHostBuilder CreateHostBuilder(IConfiguration configuration, string[] args) => |
14 | 42 | Host.CreateDefaultBuilder(args) |
15 | 43 | .ConfigureWebHostDefaults(webBuilder => |
16 | 44 | { |
17 | 45 | webBuilder.UseStartup<Startup>(); |
| 46 | + webBuilder.UseConfiguration(configuration); |
| 47 | + webBuilder.UseSerilog(); |
18 | 48 | }); |
| 49 | + |
| 50 | + private static ILogger CreateSerilogLogger(IConfiguration configuration) |
| 51 | + { |
| 52 | + return new LoggerConfiguration() |
| 53 | + .MinimumLevel.Verbose() |
| 54 | + .Enrich.WithProperty("ApplicationContext", AppName) |
| 55 | + .Enrich.FromLogContext() |
| 56 | + .Enrich.WithSpan() |
| 57 | + .WriteTo.Console() |
| 58 | + .WriteTo.Seq("http://seq") |
| 59 | + .ReadFrom.Configuration(configuration) |
| 60 | + .CreateLogger(); |
| 61 | + } |
| 62 | + |
| 63 | + private static IConfiguration GetConfiguration() |
| 64 | + { |
| 65 | + var builder = new ConfigurationBuilder() |
| 66 | + .SetBasePath(Directory.GetCurrentDirectory()) |
| 67 | + .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) |
| 68 | + .AddEnvironmentVariables(); |
| 69 | + |
| 70 | + return builder.Build(); |
| 71 | + } |
19 | 72 | } |
20 | 73 | } |
0 commit comments