Esempio n. 1
0
 private static void Main(string[] args)
 {
     using (var log = new LoggerConfiguration()
                      .ReadFrom.AppSettings()
                      .Enrich.WithProperty("Application", Assembly.GetExecutingAssembly().GetName().Name)
                      .Enrich.WithProperty("Version", Assembly.GetExecutingAssembly().GetName().Version)
                      .Enrich.WithProperty("Identifier", Process.GetCurrentProcess().Id)
                      .CreateLogger())
     {
         if (args.Length == 0)
         {
             log.Fatal("Must supply one or more job names to perform upload, see jobs.json.");
             throw new ArgumentNullException();
         }
         else
         {
             foreach (string arg in args)
             {
                 log.Verbose("Processing {arg}...", arg);
                 var uploader = new Uploader(log);
                 try
                 {
                     uploader.Process(arg);
                 }
                 catch (Exception ex)
                 {
                     log.Fatal(ex, "Fatal exception: {ErrorMessage}", ex.Message);
                 }
             }
         }
     }
 }
Esempio n. 2
0
        private static void Main()
        {
            string fiddlerAppDataPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "UoFiddler");
            string logFileName        = Path.Combine(fiddlerAppDataPath, "log", "uo-fiddler-log.txt");

            var logger = new LoggerConfiguration()
                         .MinimumLevel.Information()
                         .WriteTo.File(logFileName,
                                       rollingInterval: RollingInterval.Day,
                                       rollOnFileSizeLimit: true,
                                       fileSizeLimitBytes: 44040192)
                         .CreateLogger();

            logger.Information("UOFiddler - Application start.");

            try
            {
                FiddlerAppContext fiddlerAppContext = new FiddlerAppContext(logger);
                Application.Run(fiddlerAppContext);
            }
            catch (Exception err)
            {
                Clipboard.SetDataObject(err.ToString(), true);
                logger.Fatal("UOFiddler - unhandled exception caught!");
                logger.Fatal("{err}", err);
                Application.Run(new ExceptionForm(err));
                logger.Fatal("UOFiddler - unhandled exception - Application exit.");
            }
        }
        public void InitializeLogger()
        {
            UwpErrorLogger uwpErrorLogger = new UwpErrorLogger();
            var            log            = new LoggerConfiguration().WriteTo.Console().WriteTo.Logger(x => uwpErrorLogger.AddToList(x.ToString())).CreateLogger();

            log.Fatal("fatal");
            log.Error("error");
            log.Fatal("fatal2");
            uwpErrorLogger.ReadList();
        }
Esempio n. 4
0
        static void Main(string[] args)
        {
            Logger log = new LoggerConfiguration()
                         .MinimumLevel.Verbose()
                         .Enrich.FromLogContext()
                         .Enrich.WithProperty("MyLabelPropertyName", "MyPropertyValue")
                         .Enrich.WithThreadId()
                         .WriteTo.Console()
                         .WriteTo.LokiHttp(() => new LokiSinkConfiguration {
                LokiUrl          = "http://*****:*****@Position} in {Elapsed:000} ms.", position, 34);

            using (LogContext.PushProperty("A", 1))
            {
                log.Warning("Warning with Property A");
                log.Fatal("Fatal with Property A");
            }

            using (LogContext.PushProperty("MyAppendPropertyName", 1))
            {
                log.Warning("Warning with Property MyAppendPropertyName");
                log.Fatal("Fatal with Property MyAppendPropertyName");
            }

            log.Dispose();
        }
Esempio n. 5
0
        static void Main(string[] args)
        {
            var logger = new LoggerConfiguration()
                         .WriteTo.File("logs.txt", outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}")
                         .CreateLogger();

            try
            {
                logger.Information("Bot started");

                var playerRepository  = new PlayerRepository(new DbContextOptionsBuilder <FootballBotDbContext>().UseSqlite("Filename=./BotDb.db").Options);
                var teamSet           = new TeamsController(playerRepository);
                var messageController = new MessageController(playerRepository, teamSet, logger);
                var scheduler         = new Scheduler(messageController, teamSet, playerRepository, logger);

                messageController.Run();
                scheduler.Run();

                Thread.Sleep(Timeout.Infinite);
            }
            catch (Exception ex)
            {
                logger.Fatal(ex, "FATAL ERROR");
                try { new MessageController(null, null, logger).SendTextMessageToBotOwnerAsync($"Ошибка приложения: {ex.Message}").Wait(); }
                catch { }
                throw;
            }
        }
Esempio n. 6
0
        public async Task <IActionResult> DeleteTopics([FromRoute] string id)
        {
            var logger = new LoggerConfiguration()
                         .WriteTo.Sentry(_configuration.GetConnectionString("SENTRY"))
                         .WriteTo.Console()
                         .Enrich.FromLogContext()
                         .CreateLogger();

            try
            {
                logger.Error("Запрос на удаление темы");
                using (HttpClient client = new HttpClient())
                {
                    var uri           = _configuration.GetSection("TopicsURI").Value;
                    var resultMessage = await client.DeleteAsync($"{uri}deletetopics/{id}");

                    var result = await resultMessage.Content.ReadAsStringAsync();

                    return(Ok(result));
                }
            }
            catch (Exception e)
            {
                logger.Fatal(e, "Произошла фатальная ошибка");
                return(StatusCode(StatusCodes.Status500InternalServerError, e));
            }
        }
Esempio n. 7
0
        public static int Main(string[] args)
        {
            var logsFilePath = GetLogsFilePath();
            var serilogger   = new LoggerConfiguration()
                               .WriteTo.Console()
                               .WriteTo.File(new CompactJsonFormatter(), logsFilePath, rollingInterval: RollingInterval.Minute)
                               .MinimumLevel.Debug()
                               .Enrich.FromLogContext()
                               .CreateLogger();

            Console.WriteLine($"Logs are being written to {logsFilePath}");

            // Log.Logger = serilogger;

            try
            {
                serilogger.Information("Starting web host");
                BuildWebHost(args, serilogger).Run();
                return(0);
            }
            catch (Exception ex)
            {
                serilogger.Fatal(ex, "Host terminated unexpectedly");
                return(1);
            }
            finally
            {
                // Log.CloseAndFlush();
            }
        }
Esempio n. 8
0
    static async Task Main(string[] args)
    {
        // load serilog.json to IConfiguration
        var configuration = new ConfigurationBuilder()
                            .SetBasePath(Directory.GetCurrentDirectory())
                            // reloadOnChange will allow you to auto reload the minimum level and level switches
                            .AddJsonFile(path: "serilog.json", optional: false, reloadOnChange: true)
                            .Build();

        // build Serilog logger from IConfiguration
        var log = new LoggerConfiguration()
                  .ReadFrom.Configuration(configuration)
                  .CreateLogger();

        while (true)
        {
            log.Verbose("This is a Verbose log message");
            log.Debug("This is a Debug log message");
            log.Information("This is an Information log message");
            log.Warning("This is a Warning log message");
            log.Error("This is a Error log message");
            log.Fatal("This is a Fatal log message");
            await Task.Delay(1000);
        }
    }
Esempio n. 9
0
        static void Main(string[] args)
        {
            // Check here to find out how to get this information from LogAnalytics here https://www.systemcenterautomation.com/2018/05/find-azure-log-analytics-keys/
            const string WORKSPACE_ID      = "";
            const string AUTHENTICATION_ID = "";


            var logger = new LoggerConfiguration()
                         .WriteTo.AzureAnalytics(WORKSPACE_ID, AUTHENTICATION_ID, new ConfigurationSettings
            {
                LogName = nameof(CoreConsoleLogAnalytics)
            })
                         .CreateLogger();


            logger.Fatal("{Number}: {Application} {severity} log", 1, nameof(CoreConsoleLogAnalytics), "Fatal");
            logger.Error("{Number}: {Application} {severity} log", 1, nameof(CoreConsoleLogAnalytics), "Error");
            logger.Warning("{Number}: {Application} {severity} log", 2, nameof(CoreConsoleLogAnalytics), "Warning");
            logger.Information("{Number}: {Application} {severity} log", 2, nameof(CoreConsoleLogAnalytics), "Information");
            logger.Debug("{Number}: {Application} {severity} log", 3, nameof(CoreConsoleLogAnalytics), "Debug");
            logger.Verbose("{Number}: {Application} {severity} log", 3, nameof(CoreConsoleLogAnalytics), "Verbose");

            logger.Dispose();

            Console.WriteLine("Waiting 10secs for logs to be written");
            Thread.Sleep(1000 * 10);
        }
Esempio n. 10
0
        public static void Main(string[] args)
        {
            // Wait for RabbitMQ
            Thread.Sleep(10000);

            var config = new RabbitMQClientConfiguration
            {
                Port         = 5672,
                DeliveryMode = RabbitMQ.RabbitMQDeliveryMode.Durable,
                Exchange     = "serilog-sink-exchange",
                Username     = "******",
                Password     = "******",
                ExchangeType = "fanout"
            };

            config.Hostnames.Add("rabbitmq");

            var logger = new LoggerConfiguration()
                         .WriteTo.RabbitMQ((clientConfiguration, sinkConfiguration) => {
                clientConfiguration.From(config);
                sinkConfiguration.TextFormatter = new JsonFormatter();
            })
                         .MinimumLevel.Verbose()
                         .CreateLogger();

            logger.Verbose("Verbose log entry");
            logger.Debug("Debug log entry");
            logger.Information("Information log entry");
            logger.Warning("Warning log entry");
            logger.Error("Error log entry");
            logger.Fatal("Fatal log entry");
        }
        public static void Main(string[] args)
        {
            var configuration = new ConfigurationBuilder()
                                .AddJsonFile("appsettings.json")
                                .Build();

            var logger = new LoggerConfiguration()
                         .ReadFrom.Configuration(configuration)
                         .CreateLogger();



            try
            {
                logger.Information("Starting up");
                CreateWebHostBuilder(args).Build().Run();
            }
            catch (Exception ex)
            {
                logger.Fatal(ex, "Application start-up failed");
            }
            //finally
            //{
            //    Log.CloseAndFlush();
            //}
        }
Esempio n. 12
0
        static void Main(string[] args)
        {
            Serilog.Debugging.SelfLog.Enable(msg => Console.WriteLine(msg));
            Serilog.Sinks.Slack.SlackSink.ProxyUri        = "url:8080";
            Serilog.Sinks.Slack.SlackSink.ProxyAuthString = "Negotiate  base64encoded user:pass";
            var log = new LoggerConfiguration()
                      .MinimumLevel.Verbose()
                      //.WriteTo.Slack("C0W6DD7LZ", "xoxp-13773446566-13774642576-72300718082-1d35369b22", LevelAlias.Maximum)
                      .WriteTo.Slack("Slack URL"
                      //,(LogEvent l) => l.RenderMessage()
                                     )
                      .CreateLogger();

            try
            {
                log.Verbose("This is an verbose message!");
                log.Debug("This is an debug message!");
                log.Information("This is an information message!");
                log.Warning("This is an warning message!");
                log.Error("This is an error message!");
                throw new Exception("This is an exception!");
            }
            catch (Exception exception)
            {
                log.Fatal(exception, "Exception catched at Main.");
            }
            Console.ReadLine();
        }
Esempio n. 13
0
        /// <summary>
        /// Start here
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            var log = new LoggerConfiguration()

                      .WriteTo.ColoredConsole(outputTemplate: " {Timestamp:HH:mm} [{Level}] ({ThreadId}) {Message}{NewLine}{Exception}")
                      .MinimumLevel.Verbose()

                      .WriteTo.File("log/log.txt", rollingInterval: RollingInterval.Day) //

                      .WriteTo.File("log/Xog.txt", retainedFileCountLimit: 4, rollingInterval: RollingInterval.Minute)

                      .WriteTo.File("log/Yog.txt", fileSizeLimitBytes: 1024, retainedFileCountLimit: 5, rollOnFileSizeLimit: true)

                      .WriteTo.SQLite("db/test.db", tableName: "dataLog")

                      .CreateLogger();

            var userId = "mgasrs";

            log.Debug($"User id is: {userId}");
            log.Fatal("this is fatal");             // Highest
            log.Error("this is error");
            log.Warning("this is warning");
            log.Information("this is info");
            log.Debug("this is debug");
            log.Verbose("this is verbose");         // Lowest


            Console.ReadKey();
        }
Esempio n. 14
0
        public static int Main(string[] args)
        {
            var outputTemplate = "[{Timestamp:HH:mm:ss} {Level:u3} {SourceContext}] {Message:lj}{NewLine}{Exception}";

            using var logger = new LoggerConfiguration()
                               .MinimumLevel.Verbose()
                               .Enrich.WithProperty("ApplicationContext", Program.AppName)
                               .Enrich.FromLogContext()
                               .WriteTo.Console(outputTemplate: outputTemplate)
                               .CreateLogger();

            try
            {
                logger.Information("Starting host");

                CreateHostBuilder(args).Build().Run();

                return(0);
            }
            catch (Exception ex)
            {
                logger.Fatal(ex, "Host terminated unexpectedly");

                return(1);
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }
Esempio n. 15
0
        public void WhenInvalidApiKeyProvided_OnSinkSend_TraceAndSerilogSelfLogPopulated()
        {
            var serilogSelfLogWriter = new StringWriter();

            Debugging.SelfLog.Enable(serilogSelfLogWriter);

            var traceWriter = new StringWriter();

            Trace.Listeners.Add(new TextWriterTraceListener(traceWriter));

            var logger = new LoggerConfiguration()
                         .WriteTo.LogglyBulk("!!FAKE KEY!!", new[] { "!!FAKE TAG!!" }).CreateLogger();

            logger.Fatal("!!FAKE MESSAGE!!");

            logger.Dispose();

            var traceResult = traceWriter.ToString();

            Assert.IsFalse(string.IsNullOrWhiteSpace(traceResult));

            var selfLogResult = serilogSelfLogWriter.ToString();

            Assert.IsFalse(string.IsNullOrWhiteSpace(selfLogResult));

            Assert.IsTrue(traceResult.Contains(
                              "Exception posting to loggly System.Net.Http.HttpRequestException: Response status code does not indicate success"));

            Assert.IsTrue(selfLogResult.Contains(
                              "Exception posting to loggly System.Net.Http.HttpRequestException: Response status code does not indicate success"));

            Console.WriteLine(traceResult);
            Console.WriteLine(selfLogResult);
        }
Esempio n. 16
0
        public async Task <IActionResult> FormsGet([FromRoute] string u_uid, string m_uid)
        {
            var logger = new LoggerConfiguration()
                         .WriteTo.Sentry(_configuration.GetConnectionString("SENTRY"))
                         .WriteTo.Console()
                         .Enrich.FromLogContext()
                         .CreateLogger();

            try
            {
                logger.Error("Получение форм");
                using HttpClient client = new HttpClient();
                var uri           = _configuration.GetSection("ComplaintsURI").Value;
                var resultMessage = await client.GetAsync($"{uri}getforms/useruid={u_uid}/mundepuid={m_uid}");

                var result = await resultMessage.Content.ReadAsStringAsync();

                return(Ok(result));
            }
            catch (Exception e)
            {
                logger.Fatal(e, "Произошла фатальная ошибка");
                return(StatusCode(StatusCodes.Status500InternalServerError, e));
            }
        }
Esempio n. 17
0
        public async Task <IActionResult> FormEdit([FromBody] object model)
        {
            var logger = new LoggerConfiguration()
                         .WriteTo.Sentry(_configuration.GetConnectionString("SENTRY"))
                         .WriteTo.Console()
                         .Enrich.FromLogContext()
                         .CreateLogger();

            try
            {
                logger.Error("Изменение формы");
                using HttpClient client = new HttpClient();
                var uri           = _configuration.GetSection("ComplaintsURI").Value;
                var resultMessage = await client.PostAsJsonAsync($"{uri}editforms", model);

                var result = await resultMessage.Content.ReadAsStringAsync();

                return(Ok(result));
            }
            catch (Exception e)
            {
                logger.Fatal(e, "Произошла фатальная ошибка");
                return(StatusCode(StatusCodes.Status500InternalServerError, e));
            }
        }
        public async Task <IActionResult> GetFitnessRecords()
        {
            var logger = new LoggerConfiguration()
                         .WriteTo.Sentry("https://[email protected]/5721941")
                         .Enrich.FromLogContext()
                         .CreateLogger();

            try
            {
                logger.Error("Новый поиск упражнений");

                using (HttpClient client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Add("sentry-header", "123");
                    //Реализация обращения к сервису
                    var url           = _configuration.GetSection("FitnessRecordsUri").Value;
                    var resultMessage = await client.GetAsync($"{url}exercises");

                    resultMessage.EnsureSuccessStatusCode();
                    var result = await resultMessage.Content.ReadAsStringAsync();

                    return(Ok(result));
                }
            }
            catch (Exception e)
            {
                logger.Fatal(e, "Произошла фатальная ошибка");
                return(StatusCode(StatusCodes.Status500InternalServerError, e));
            }
        }
Esempio n. 19
0
        static void Main(string[] args)
        {
            RegisterServices();

            var service = _serviceProvider.GetService <IService>();

            service.TestLog();

            Console.WriteLine("Hello World!");
            Console.WriteLine("------------");
            Console.WriteLine("------------");
            Console.WriteLine("------------");
            Console.WriteLine("");
            Console.WriteLine("");
            Console.WriteLine("");
            using (var log = new LoggerConfiguration()
                             .WriteTo.Console(restrictedToMinimumLevel: Serilog.Events.LogEventLevel.Information)
                             .WriteTo.File("log/log.txt", Serilog.Events.LogEventLevel.Error)
                             .CreateLogger())
            {
                log.Information("Hello from Information Serilog");
                log.Warning("Hello from Warning Serilog");
                log.Error("Hello from Error Serilog");
                log.Fatal("Hello from Fatal Serilog");
            }
        }
Esempio n. 20
0
        static int Main(string[] args)
        {
            var configuration = new ConfigurationBuilder()
                                .SetBasePath(Directory.GetCurrentDirectory())
                                .AddJsonFile("appsettings.json", false)
                                .Build();

            var logger = new LoggerConfiguration()
                         .ReadFrom.Configuration(configuration)
                         .CreateLogger();

            try
            {
                var worker = new MyClass(logger);
                worker.Start();
                logger.Information("The work finished at: {DateTime}", DateTime.Now);
                return(0);
            }
            catch (Exception ex)
            {
                logger.Fatal(ex, "The application crashed");
                return(1);
            }
            finally
            {
                logger.Dispose();
            }
        }
Esempio n. 21
0
        static void Main(string[] args)
        {
            var loggingLevelSwitch = new LoggingLevelSwitch(LogEventLevel.Verbose);

            var logger = new LoggerConfiguration()
                         .MinimumLevel.ControlledBy(loggingLevelSwitch)
                         .WriteTo.Console(LogEventLevel.Verbose)
                         .CreateLogger();

            while (true)
            {
                logger.Verbose("Verbose");

                logger.Debug("Debug");

                logger.Information("Information");

                logger.Warning("Warning");

                logger.Error("Error");

                logger.Fatal("Fatal");

                Console.WriteLine($"Minimum level is {loggingLevelSwitch.MinimumLevel}");

                Console.WriteLine("--------------------------------------------------");

                Thread.Sleep(4000);
            }
        }
Esempio n. 22
0
        public void LoggingLevelSwitchDynamicallyChangesLevel()
        {
            var events = new List <LogEvent>();
            var sink   = new DelegatingSink(events.Add);

            var levelSwitch = new LoggingLevelSwitch(LogEventLevel.Information);

            var log = new LoggerConfiguration()
                      .MinimumLevel.ControlledBy(levelSwitch)
                      .WriteTo.Sink(sink)
                      .CreateLogger()
                      .ForContext <LoggerTests>();

            log.Debug("Suppressed");
            log.Information("Emitted");
            log.Warning("Emitted");

            // Change the level
            levelSwitch.MinimumLevel = LogEventLevel.Error;

            log.Warning("Suppressed");
            log.Error("Emitted");
            log.Fatal("Emitted");

            Assert.Equal(4, events.Count);
            Assert.True(events.All(evt => evt.RenderMessage() == "Emitted"));
        }
Esempio n. 23
0
        public static int Main(string[] args)
        {
            using var hostLogger = new LoggerConfiguration()
                                   .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
                                   .Enrich.WithUtcTimestamp()
                                   .WriteTo.HostLevelLog()
                                   .CreateLogger();

            try
            {
                hostLogger.Information("Starting web host");

                var host = CreateHostBuilder(args).Build();

                PrepareApplication(host);

                host.Run();

                hostLogger.Information("Shutdown web host");

                return(0);
            }
            catch (Exception ex)
            {
                hostLogger.Fatal(ex, "Host terminated unexpectedly");

                return(1);
            }
        }
Esempio n. 24
0
        public async Task <IActionResult> GetTopics()
        {
            var logger = new LoggerConfiguration()
                         .WriteTo.Sentry(_configuration.GetSection("SENTRY").Value)
                         .WriteTo.Console()
                         .Enrich.FromLogContext()
                         .CreateLogger();

            try
            {
                logger.Error("Запрос на поиск тем");
                using HttpClient client = new HttpClient();
                client.DefaultRequestHeaders.Add("sentry-header", "123");
                var url           = _configuration.GetSection("TopicsURI").Value;
                var resultMessage = await client.GetAsync($"{url}gettopics");

                resultMessage.EnsureSuccessStatusCode();
                var result = await resultMessage.Content.ReadAsStringAsync();

                return(Ok(result));
            }
            catch (Exception e)
            {
                logger.Fatal(e, "Произошла фатальная ошибка");
                return(StatusCode(StatusCodes.Status500InternalServerError, e));
            }
        }
Esempio n. 25
0
        public void LoggingLevelSwitchDynamicallyChangesLevel()
        {
            var events = new List<LogEvent>();
            var sink = new DelegatingSink(events.Add);

            var levelSwitch = new LoggingLevelSwitch(LogEventLevel.Information);

            var log = new LoggerConfiguration()
                .MinimumLevel.ControlledBy(levelSwitch)
                .WriteTo.Sink(sink)
                .CreateLogger()
                .ForContext<LoggerTests>();

            log.Debug("Suppressed");
            log.Information("Emitted");
            log.Warning("Emitted");

            // Change the level
            levelSwitch.MinimumLevel = LogEventLevel.Error;

            log.Warning("Suppressed");
            log.Error("Emitted");
            log.Fatal("Emitted");

            Assert.Equal(4, events.Count);
            Assert.True(events.All(evt => evt.RenderMessage() == "Emitted"));
        }
Esempio n. 26
0
            // Sets up a log which outputs to the console and to the logs/ directory.
            static ILogger SetUpLog()
            {
                Directory.CreateDirectory("logs");

                Console.InputEncoding  = Encoding.UTF8;
                Console.OutputEncoding = Encoding.UTF8;

                var log = new LoggerConfiguration()
                          .Destructure.UsingAttributes()
                          .MinimumLevel.Is(MinimumLogLevel)
                          .WriteTo.Console(
                    outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Name}: {Message:l}{NewLine}{Exception}",
                    theme: AnsiConsoleTheme.Code)
                          .WriteTo.File(Path.Combine("logs", "log-.txt"),
                                        outputTemplate:
                                        "[{Timestamp:yyyy-MM-dd HH:mm:ss} {Level:u3}] {Name}: {Message:l}{NewLine}{Exception}",
                                        rollingInterval: RollingInterval.Day,
                                        rollOnFileSizeLimit: true,
                                        fileSizeLimitBytes: 2 << 20)
                          .CreateLogger()
                          .ForContext("Name", "orion-launcher");

                AppDomain.CurrentDomain.UnhandledException +=
                    (sender, eventArgs) => log.Fatal(
                        eventArgs.ExceptionObject as Exception, Resources.UnhandledExceptionMessage);

                return(log);
            }
Esempio n. 27
0
        public static void Main(string[] args)
        {
            var startupLogger = new LoggerConfiguration()
                                .Enrich.FromLogContext()
                                .WriteTo.Console()
                                .WriteTo.File(new RenderedCompactJsonFormatter(),
                                              "startup_log.ndjson",
                                              buffered: false,
                                              rollingInterval: RollingInterval.Day,
                                              retainedFileCountLimit: 10
                                              ).CreateLogger();

            try
            {
                startupLogger.Information("Starting up");
                CreateHostBuilder(args).Build().Run();
            }
            catch (Exception e)
            {
                startupLogger.Fatal(e, "Application start-up failed!");
            }
            finally
            {
                Log.CloseAndFlush();
                startupLogger.Dispose();
            }
        }
Esempio n. 28
0
        private static async Task Main(string[] args)
        {
            var logger = new LoggerConfiguration()
                         .MinimumLevel.Is(LogEventLevel.Debug)
                         .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
                         .MinimumLevel.Override("System", LogEventLevel.Warning)
                         .MinimumLevel.Override("Microsoft.Hosting.Lifetime", LogEventLevel.Information)
                         .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss.fff} {Level:u3}] {Message:lj} {NewLine}{Exception}")
                         .CreateLogger();

            try
            {
                await Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(
                    h => h.UseStartup <Startup>()
                    .ConfigureLogging(
                        l => l.ClearProviders()
                        .SetMinimumLevel(LogLevel.Trace)
                        .AddSerilog(logger)
                        )
                    .UseUrls("http://localhost:5000")
                    )
                .Build()
                .RunAsync();
            }
            catch (Exception ex)
            {
                logger.Fatal(ex, "Host terminated unexpectedly");
            }
            finally
            {
                logger.Dispose();
            }
        }
Esempio n. 29
0
        internal static Task Main(string[] args)
        {
            var logger = new LoggerConfiguration()
                         .MinimumLevel.Debug()
                         .WriteTo.RollingFile(Path.Combine(AppContext.BaseDirectory, "logs\\{Date}.txt"))
                         .WriteTo.Console(theme: AnsiConsoleTheme.Literate)
                         .CreateLogger();

            try
            {
                var hostBuilder = Host.CreateDefaultBuilder()
                                  .ConfigureAppConfiguration(c => c.AddJsonFile("appSettings.json", false, true).Build())
                                  .ConfigureServices(ConfigureServices);

                return(Environment.UserInteractive
                       ? hostBuilder.RunConsoleAsync()
                       : hostBuilder.UseServiceBaseLifetime().Build().RunAsync());
            }
            catch (Exception e)
            {
                logger.Fatal(e, "Host terminated unexpectedly");
                throw;
            }
            finally
            {
                logger.Dispose();
            }
        }
Esempio n. 30
0
        public static int Main(string[] args)
        {
            var logger = new LoggerConfiguration()
                         .MinimumLevel.Information()
                         .Enrich.FromLogContext()
                         .WriteTo.Console(outputTemplate: LogTemplate, theme: AnsiConsoleTheme.Code)
                         .CreateLogger();

            try
            {
                logger.Information("Starting host...");
                CreateHostBuilder(args).Build().Run();
                logger.Information("Stopping host...");

                return(0);
            }
            catch (Exception ex)
            {
                logger.Fatal(ex, "Host terminated unexpectedly.");

                return(1);
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }
Esempio n. 31
0
        static void Main(string[] args)
        {
            var keepRunning = args.Length > 0 && args[0] == "--background";
            var asmName     = Assembly.GetExecutingAssembly().GetName();
            var logger      = new LoggerConfiguration()
                              .WriteTo.Console()
                              .WriteTo.File($"{asmName.Name}.log")
                              .CreateLogger();

            PatcherConfig configuration;

            if (!File.Exists(PatcherConfig.FILE_PATH))
            {
                logger.Error($"{PatcherConfig.FILE_PATH} doesn't exist. Creating default configuration...");
                configuration = new PatcherConfig()
                {
                    FilesDir       = "path/to/mkdd/files/directory",
                    ModsDir        = "path/to/mods/directory",
                    BinDir         = "path/to/mods/directory/.bin",
                    OutDir         = "path/to/mkdd/files/directory",
                    CacheDir       = "path/to/mods/directory/.cache",
                    ArcPackPath    = "Tools/LunaboyRarcTools/ArcPack.exe",
                    ArcExtractPath = "Tools/LunaboyRarcTools/ArcExtract.exe",
                };
            }
            else
            {
                configuration = PatcherConfig.Load(PatcherConfig.FILE_PATH);
            }

            logger.Information($"{asmName.Name} {asmName.Version.Major}.{asmName.Version.Minor}.{asmName.Version.Revision} by TGE ({DateTime.Now.Year})\n");

#if !DEBUG
            try
            {
#endif
            var modDb   = new ModDb(logger, configuration, configuration.ModsDir);
            var patcher = new Patcher(logger, configuration, modDb);
            patcher.Patch(MergeOrder.TopToBottom);

            if (keepRunning)
            {
                while (true)
                {
                    patcher.Patch(MergeOrder.TopToBottom);
                    Console.WriteLine("Press any key to patch");
                    Console.ReadKey();
                }
            }
#if !DEBUG
        }

        catch (Exception e)
        {
            logger.Fatal($"An unhandled exception occured: {e.Message}\nThe program will now exit.");
        }
#endif
        }