using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Serilog; using Serilog.Core; using Serilog.Events; using Serilog.Sinks.MSSqlServer; using System; using System.Diagnostics; using System.IO; using System.Linq; namespace NetworkResurrector.Server { public class Program { public static void Main(string[] args) { var isConsole = Debugger.IsAttached || args.Contains("--console"); if (!isConsole) { var pathToExe = Process.GetCurrentProcess().MainModule.FileName; var pathToContentRoot = Path.GetDirectoryName(pathToExe); Directory.SetCurrentDirectory(pathToContentRoot); } var configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) .Build(); var connectionString = configuration.GetConnectionString("DatabaseConnection"); var loggingLevelParam = configuration.GetValue("Logging:LogLevel:Default"); Enum.TryParse(loggingLevelParam, out LogEventLevel loggingLevel); var loggingLevelSwitch = new LoggingLevelSwitch(loggingLevel); var columnOptions = new ColumnOptions(); columnOptions.Store.Remove(StandardColumn.Properties); columnOptions.Store.Remove(StandardColumn.MessageTemplate); columnOptions.Store.Add(StandardColumn.LogEvent); Log.Logger = new LoggerConfiguration() .MinimumLevel.ControlledBy(loggingLevelSwitch) .MinimumLevel.Override("Microsoft", LogEventLevel.Warning) .Enrich.FromLogContext() .WriteTo.Console() .WriteTo.MSSqlServer(connectionString, "__Logs", autoCreateSqlTable: true, columnOptions: columnOptions) .CreateLogger(); try { var urls = configuration.GetValue("urls"); Log.Information("Starting network resurrector API..."); Log.Information($"API listening on {urls}"); Console.WriteLine("Application started. Press Ctrl+C to shut down."); CreateHostBuilder(args, configuration, !isConsole).Build().Run(); } catch (Exception ex) { Log.Fatal(ex, "Network resurrector API host terminated unexpectedly"); } finally { Log.CloseAndFlush(); } } public static IHostBuilder CreateHostBuilder(string[] args, IConfiguration configuration, bool useWindowsService) { var builder = Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup() .UseConfiguration(configuration) .UseSerilog(); }); if (useWindowsService) builder.UseWindowsService(); return builder; } } }