예제 #1
0
        public static void Main(string[] args)
        {
            IsShuttingDown = false;

            var loggerConfig = new LoggerConfiguration()
                               .MinimumLevel.Debug()
                               .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
                               .MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning)
                               .Enrich.FromLogContext()

                               .WriteTo.File("log/detail-.txt",
                                             //?restrictedToMinimumLevel: LogEventLevel.Warning,
                                             rollingInterval: RollingInterval.Day,
                                             retainedFileCountLimit: 7,
                                             shared: true,
                                             outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss} {Level:u3} {Message:lj}{NewLine}{Exception}"
                                             )
                               // .WriteTo.File("log/info-.txt",
                               //         rollingInterval: RollingInterval.Day,
                               //         shared: true,
                               //         outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss} {Level:u3} {Message:lj}{NewLine}{Exception}",
                               //         restrictedToMinimumLevel: LogEventLevel.Information
                               //         )
            ;

            try
            {
                CTS = new CancellationTokenSource();

                var isService = args.Length == 1 && args[0].Equals("--service", StringComparison.OrdinalIgnoreCase);
                var justRun   = args.Length == 1 && args[0].Equals("--run", StringComparison.OrdinalIgnoreCase);

                if (isService)
                {
                    var pathToExe = Process.GetCurrentProcess().MainModule.FileName;
                    var pathToContentRootService = Path.GetDirectoryName(pathToExe);
                    Directory.SetCurrentDirectory(pathToContentRootService);
                }
                else if (!Debugger.IsAttached && !justRun)
                {
                    TerminalUI.Init();
                    return;
                }
                else
                {
                    loggerConfig.WriteTo.Console();
                }

                Log.Logger = loggerConfig.CreateLogger();

                var pathToContentRoot = Directory.GetCurrentDirectory();

                if (Debugger.IsAttached)
                {
                    // var pathToExe = Process.GetCurrentProcess().MainModule.FileName;
                    //  pathToContentRoot = Path.GetDirectoryName(pathToExe);
                }
                else
                {
                    // now relying on serilog
                    // OverrideStdout();
                }

                AppDomain.CurrentDomain.UnhandledException += (sender, e) =>
                {
                    var isTerminating = e.IsTerminating;

                    Log.Fatal("Unhandled exception", e.ExceptionObject);
                    ExceptionLogger.LogException(e.ExceptionObject as Exception);
                };

                AppConfigSettings appConfigSettings = null;

                try
                {
                    var appSettingsJson = File.ReadAllText("./appsettings.json");

                    appConfigSettings = System.Text.Json.JsonSerializer.Deserialize <AppConfigSettings>(appSettingsJson);
                }
                catch (Exception ex)
                {
                    Log.Error(ex, "Failed to read appsettings.json");
                }

                _startDate = DateTime.Now;

                var _ = UptimeLogger.LogServerUptimeAsync();

                Log.Information($"Application started with process id {System.Diagnostics.Process.GetCurrentProcess().Id}.");

                // I forget what the different msg types look like
                Log.Warning("This is what a warning looks like");
                Log.Error("This is what an error looks like");
                Log.Fatal("This is what a fatal error looks like");

                Log.Information("Loading users");
                UserManagement.LoadUsersFromFile();

                Log.Information("Initialising exception logger");
                ExceptionLogger.Instance.Init();

                Log.Information("Loading settings");
                SettingsInstance.LoadSettingsFromFile();

                Log.Information("Initialising real-time tracker");
                RealtimeTrackerThread.Instance.Init();

                if (appConfigSettings?.AppSettings?.Startup?.HealthMonitor ?? false)
                {
                    Log.Information("Initialising jsDAL health monitor");
                    jsDALHealthMonitorThread.Instance.Init();
                }
                else
                {
                    Log.Information("jsDAL health monitor not configured to run at startup");
                }

                if (appConfigSettings?.AppSettings?.Startup?.DataCollector ?? false)
                {
                    Log.Information("Initialising data collector");
                    DataCollectorThread.Instance.Init();
                }
                else
                {
                    Log.Information("Data collector not configured to run at startup");
                }

                Log.Information("Initialising inline module manifest");
                InlineModuleManifest.Instance.Init();


                Log.Information("Configuring global culture");
                var globalCulture = new System.Globalization.CultureInfo("en-US");

                // set global culture to en-US - will help with things like parsing numbers from Javascript(e.g. 10.123) as double/decimal even if server uses a comma as decimal separator for example
                CultureInfo.DefaultThreadCurrentCulture   = globalCulture;
                CultureInfo.DefaultThreadCurrentUICulture = globalCulture;

                Log.Information("Building web host");
                var builder = BuildWebHost(pathToContentRoot, args);
                var host    = builder.Build();

                if (isService)
                {
                    host.RunAsCustomService();
                }
                else
                {
                    host.RunAsync();

                    Console.WriteLine("\r\nPress CTRL+X to shutdown server");

                    while (true)
                    {
                        var keyInfo = Console.ReadKey(true);

                        if (keyInfo.Key == ConsoleKey.X && (keyInfo.Modifiers & ConsoleModifiers.Control) == ConsoleModifiers.Control)
                        {
                            //host.StopAsync();
                            ShutdownAllBackgroundThreads();
                            break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "Application terminated unexpectedly");
                SessionLog.Exception(ex);

                ShutdownAllBackgroundThreads();
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }