Пример #1
0
 protected override void OnStartup(object sender, StartupEventArgs e)
 {
     try
     {
         base.OnStartup(sender, e);
         DisplayRootViewFor <MainViewModel>();
     }
     catch (Exception ex)
     {
         serilog.Fatal(ex.Message);
         serilog.Fatal(ex.StackTrace);
     }
 }
Пример #2
0
 /// <summary>
 /// Start the given host and log failing exceptions.
 /// </summary>
 /// <param name="host">The host to start.</param>
 /// <param name="cancellationToken">A token to allow one to stop the host.</param>
 private async Task _StartWithHost(IHost host, CancellationToken cancellationToken)
 {
     try
     {
         _logger.Information("Running as {Name}", Environment.UserName);
         _logger.Information("Version: {Version}", Assembly.GetExecutingAssembly().GetName().Version.ToString(3));
         _logger.Information("Data directory: {DataDirectory}", GetDataDirectory());
         await host.RunAsync(cancellationToken);
     }
     catch (Exception ex)
     {
         _logger.Fatal(ex, "Unhandled exception");
     }
 }
Пример #3
0
        public static int Main(string[] args)
        {
            try {
                Logger = new LoggerConfiguration()
                         .WriteTo.ColoredConsole(outputTemplate: "[{Timestamp:HH:mm}] {Message}{NewLine}{Exception}")
                         .CreateLogger();

                try {
                    SafeMain();
                }
                catch (Exception ex) {
                    Logger.Fatal(ex, "Impostor host failed.");
                    return(ex.HResult);
                }
            }
            catch (Exception ex) {
                var consoleColor = Console.ForegroundColor;
                Console.ForegroundColor = ConsoleColor.Red;
                try {
                    Console.Write(ex.ToString());
                }
                finally {
                    Console.ForegroundColor = consoleColor;
                }
                return(ex.HResult);
            }

            return(0);
        }
Пример #4
0
 public void Fatal(string template, params object[] values)
 {
     if (_inner.IsEnabled(LogEventLevel.Fatal))
     {
         _inner.Fatal(template, values);
     }
 }
Пример #5
0
        /// <inheritdoc />
        public Task LogMessage(LogMessage message)
        {
            switch (message.Severity)
            {
            case LogSeverity.Error:
            case LogSeverity.Critical:
                _logger.Fatal($"{message.Source}: {message.Message} {message.Exception}");
                break;

            case LogSeverity.Warning:
                _logger.Warning($"{message.Source}: {message.Message} {message.Exception}");
                break;

            case LogSeverity.Info:
                _logger.Information($"{message.Source}: {message.Message} {message.Exception}");
                break;

            case LogSeverity.Verbose:
                _logger.Verbose($"{message.Source}: {message.Message} {message.Exception}");
                break;

            case LogSeverity.Debug:
                _logger.Debug($"{message.Source}: {message.Message} {message.Exception}");
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            return(Task.CompletedTask);
        }
Пример #6
0
        public static async Task <string> GetRemoteJsonContentAsync(string url, string schema)
        {
            try
            {
                string content;

                content = await GetRemoteJsonContentAsync(url);

                var validateResponse =
                    JsonSchemaValidator.Validate(new JsonValidateRequest()
                {
                    Json = content, Schema = schema
                });
                if (!validateResponse.Valid)
                {
                    throw new Exception(validateResponse.Errors[0].Message);
                }

                return(content);
            }
            catch (Exception e)
            {
                logger.Fatal("Exception Caught:{0}", e.Message);
            }
            return(null);
        }
Пример #7
0
        public static void Main()
        {
            Logger = new LoggerConfiguration()
                     .Enrich.WithMachineName()
                     .Enrich.FromLogContext()
                     .WriteTo.LiterateConsole()
                     .WriteTo.Async(a => a
                                    .RollingFile(
                                        pathFormat: "data/logs/log-{Date}.txt",
                                        buffered: true
                                        ))
                     .CreateLogger();

            try
            {
                var           sep  = Path.DirectorySeparatorChar;
                DirectoryInfo info = new DirectoryInfo(Directory.GetCurrentDirectory());

                try
                {
                    while (new FileInfo($@"{info.FullName}{sep}ClientApp{sep}boot-client.tsx").Exists == false)
                    {
                        info = info.Parent;
                    }
                    ;
                }
                catch
                {
                    info = new DirectoryInfo(Directory.GetCurrentDirectory());
                }

                Logger.Information($@"Application current directory set to {info.FullName}");

                Directory.SetCurrentDirectory(info.FullName);

                Logger.Debug("Building web server configuration");

                var host = new WebHostBuilder()
                           .UseKestrel(options => {
                    options.AddServerHeader = false;
                    options.ListenAnyIP(443, listen => {
                        listen.UseHttps("data/certs/certfile.pfx", "");
                    });
                })
                           .UseContentRoot(Directory.GetCurrentDirectory())
                           .UseStartup <Startup>()
                           .UseSerilog(Logger)
                           .Build();

                Logger.Debug("Starting web server");
                host.Run();
            }
            catch (Exception e) {
                Logger.Fatal("Unknown exception in web server caused failure", e);
            }
            finally {
                Log.CloseAndFlush();
            }
        }
Пример #8
0
 private void LogExceptions(Serilog.ILogger logger)
 {
     if (LogUnhandledExceptions)
     {
         AppDomain.CurrentDomain.UnhandledException += (s, e) =>
         {
             try
             {
                 logger.Fatal("{@Sender} {@UnhandledException}", s, e);
             }
             catch (Exception ex)
             {
                 logger.Fatal("Exception thrown while showing exception: {@Exception}", ex);
             }
         };
     }
 }
        public string Schedule => "*/1 * * * *";  // every 1 minute
        private async Task <RemoteUrls> GetRemoteUrlsAsync(string url, bool validateSchema = false)
        {
            try
            {
                var schemaUrl = url.Replace(".json", ".schema.json");
                var schema    = await RemoteJsonFetch.GetRemoteJsonContentAsync(schemaUrl);

                string content = await RemoteJsonFetch.GetRemoteJsonContentAsync(url, schema);

                RemoteUrls remoteUrls;
                remoteUrls = ExternUrlsOptionConvert.FromJson(content);

                return(remoteUrls);
            }
            catch (Exception e)
            {
                logger.Fatal("Exception Caught:{0}", e.Message);
            }
            return(null);
        }
Пример #10
0
 public async Task Start()
 {
     try
     {
         await _host.RunAsync();
     }
     catch (System.Exception ex)
     {
         Logger.Fatal("Unknown error occurred: {0}", ex);
         Environment.Exit((int)ErrorCode.UnknownError);
     }
 }
Пример #11
0
        public void LogException(Exception exception, ExceptionSeverity severity)
        {
            switch (severity)
            {
            case ExceptionSeverity.Severe:
                serilogLogger.Fatal(exception, string.Empty);
                break;

            default:
                serilogLogger.Error(exception, string.Empty);
                break;
            }
        }
Пример #12
0
        public static async Task <string> FetchAsync(string url, WebRequestInit init)
        {
            try
            {
                var uri = url;
                var req = (HttpWebRequest)WebRequest.Create((string)uri);
                req.Accept = init.Accept;
                if (init.Headers != null)
                {
                    var allKeys = init.Headers.AllKeys;
                    foreach (var key in allKeys)
                    {
                        var value = init.Headers.Get(key);
                        req.Headers.Add(key, value);
                    }
                }
                var    content = new MemoryStream();
                string result;
                using (WebResponse response = await req.GetResponseAsync())
                {
                    using (Stream responseStream = response.GetResponseStream())
                    {
                        // Read the bytes in responseStream and copy them to content.
                        await responseStream.CopyToAsync(content);

                        result = Encoding.UTF8.GetString(content.ToArray());
                    }
                }
                return(result);
            }
            catch (Exception e)
            {
                logger.Fatal("Exception Caught:{0}", e.Message);
            }
            return(null);
        }
Пример #13
0
 public ResultView SendEmail()
 {
     if (_Logger == null)
     {
         _Logger = new Serilog.LoggerConfiguration()
                   .WriteTo.Email(
             fromEmail: "*****@*****.**",
             toEmail: "*****@*****.**",
             mailServer: "smtp.163.com",
             restrictedToMinimumLevel: Serilog.Events.LogEventLevel.Warning,
             networkCredential: new System.Net.NetworkCredential("*****@*****.**", "1234qwer"),
             outputTemplate: "[{Level}] {Message}{NewLine}{Exception}",
             mailSubject: "系统错误-提醒邮件")
                   .CreateLogger();
     }
     _Logger.Fatal("测试邮件 {test}", "邮件发送内容");
     return(ResultView.Success());
 }
Пример #14
0
        public void Log(string category,
                        LogLevel level,
                        string msg,
                        params object[] parameters)
        {
            var template = msg;

            if (!string.IsNullOrEmpty(category))
            {
                template = string.Format("[{0}]: {1}", category, msg);
            }

            msg = string.Format(template, parameters);

            switch (level)
            {
            case LogLevel.Trace:
                _logger.Verbose(msg);
                break;

            case LogLevel.Debug:
                _logger.Debug(msg);
                break;

            case LogLevel.Info:
                _logger.Information(msg);
                break;

            case LogLevel.Warning:
                _logger.Warning(msg);
                break;

            case LogLevel.Error:
                _logger.Error(msg);
                break;

            case LogLevel.Critical:
                _logger.Fatal(msg);
                break;
            }
        }
        private async Task ProcessMessageAsync(MessageReceivedEventArgs e)
        {
            try
            {
                if (IsRunning)
                {
                    if (await IsRelevantAsync(e.Message).ConfigureAwait(false))
                    {
                        var result = await CommandHandler.ExecuteAsync(e.Message).ConfigureAwait(false);

                        if (result == null)
                        {
                            _logger.Error($"Unknown command trigger {e.Message.Content}");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Fatal(ex, $"Unexpected error occured while Processing Message -> {e.Message}: ");
            }
        }
Пример #16
0
        private async Task <List <RazorLocation> > GetRemoteDataAsync(string url)
        {
            try
            {
                var accept = "application/json";
                var uri    = url;
                var req    = (HttpWebRequest)WebRequest.Create((string)uri);
                req.Accept = accept;
                var content = new MemoryStream();
                RazorLocationViews razorLocationViews;
                using (WebResponse response = await req.GetResponseAsync())
                {
                    using (Stream responseStream = response.GetResponseStream())
                    {
                        // Read the bytes in responseStream and copy them to content.
                        await responseStream.CopyToAsync(content);

                        string result = Encoding.UTF8.GetString(content.ToArray());
                        razorLocationViews = FromJson(result);
                    }
                }
                var now = DateTime.UtcNow;

                var query = from item in razorLocationViews.Views
                            let c = new RazorLocation(item)
                {
                    LastModified = now, LastRequested = now
                }
                select c;

                return(query.ToList());
            }
            catch (Exception e)
            {
                logger.Fatal("Exception Caught:{0}", e.Message);
            }
            return(null);
        }
Пример #17
0
        static void Main(string[] args)
        {
            httpClient.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36");
            try{
                // Two implemenations provided one uses all the API features but is more chatty
                // the other loads all data from the medications processes it and builds data tables to process
                // implementation using chatty live data
                var t1 = DoAsyncWorkLiveRequests();
                t1.Wait();
                var s1 = t1.Result;
                Console.Write(s1);

                //implementation using  data downloaded all at once
                //var t2 = DoAsyncWorkUseStaticDataFromMedications();
                //t2.Wait();
                //var s2 = t2.Result;
                //Console.Write(s2);
            }
            catch (Exception e)
            {
                Logger.Fatal(e, "Unhandled Exception ");
            }
        }
Пример #18
0
 public void Log(LogEntry entry)
 {
     /* Logging abstraction handling */
     if (entry.Severity == LoggingEventType.Debug)
     {
         _logger.Debug(entry.Exception, entry.Message);
     }
     if (entry.Severity == LoggingEventType.Information)
     {
         _logger.Information(entry.Exception, entry.Message);
     }
     else if (entry.Severity == LoggingEventType.Warning)
     {
         _logger.Warning(entry.Message, entry.Exception);
     }
     else if (entry.Severity == LoggingEventType.Error)
     {
         _logger.Error(entry.Message, entry.Exception);
     }
     else
     {
         _logger.Fatal(entry.Message, entry.Exception);
     }
 }
        protected async override Task ExecuteAsync(CancellationToken stoppingToken)
        {
            if (MAX_PER_PERIOD < MAX_ACTION_CONCURRENT)
            {
                throw new Exception("The MAX_PER_PERIOD should be more or equal to MAX_ACTION_CONCURRENT");
            }

            try
            {
                while (true)
                {
                    try
                    {
                        await ExecFeedServiceAsync(stoppingToken);
                    }
                    catch (Exception ex)
                    {
                        _logger.Error($"Se produjo un error al enviar datos: {ex.Message}, {ex.StackTrace}.");
                    }
                    // waiting an opportunity to run an action
                    //await _semaphoreSlimAction.WaitAsync(stoppingToken);
                    // waiting the last period to end
                    await _semaphoreSlimPeriod.WaitAsync(stoppingToken);

                    try
                    {
                        await ExecServiceAsync(_ordersService, stoppingToken);
                        await ExecServiceAsync(_categoryService, stoppingToken);
                        await ExecServiceAsync(_brandsService, stoppingToken);
                        await ExecServiceAsync(_specificationGroupService, stoppingToken);
                        await ExecServiceAsync(_specificationService, stoppingToken);
                        await ExecServiceAsync(_productService, stoppingToken);
                        await ExecServiceAsync(_SKUService, stoppingToken);
                        await ExecServiceAsync(_specificationValuesService, stoppingToken);
                        await ExecServiceAsync(_motosService, stoppingToken);
                        await ExecServiceAsync(_productSpecificationsService, stoppingToken);
                        await ExecServiceAsync(_SKUSpecificationsService, stoppingToken);
                        await ExecServiceAsync(_SKUFilesService, stoppingToken);
                        await ExecServiceAsync(_inventoryService, stoppingToken);
                        await ExecServiceAsync(_pricesService, stoppingToken);
                    }
                    catch (Exception ex)
                    {
                        _logger.Error($"Se produjo un error al enviar datos: {ex.Message}, {ex.StackTrace}.");
                    }
                    finally
                    {
                        _ = Task.Delay(PERIOD).ContinueWith(task =>
                        {
                            _logger.Debug("Release period sempahore");
                            _semaphoreSlimPeriod.Release(1);
                            _semaphoreSlimAction.Release(1);
                        });
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Fatal($"BackgroundWorker stopped by error {ex.Message}");
                throw;
            }
        }
Пример #20
0
 /// <summary>
 /// Log a message object with Warning level.
 /// </summary>
 /// <param name="logMessage">The message object to log.</param>
 public void LogFatal(Exception ex, string logMessage)
 {
     log.Fatal(ex, logMessage);
 }
Пример #21
0
 public void Fatal(string messageTemplate, params object[] propertyValues)
 {
     _log.Fatal(messageTemplate, propertyValues);
 }
Пример #22
0
 public void Fatal(object message, Exception ex)
 {
     _logger.Fatal(ex, $"{message}");
 }
Пример #23
0
 /// <summary>
 /// Logs the fatal.
 /// </summary>
 /// <param name="logMessage">The log message.</param>
 /// <param name="exception">The exception.</param>
 public void LogFatal(string logMessage, Exception exception)
 {
     logger.Fatal(exception, logMessage);
 }
        private async Task ExecuteImpl(CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            if (_initialized == false)
            {
                await Initialize().ConfigureAwait(false);
            }

            bool gotSomeMessages;

            do
            {
                // Always start by assuming we won't get any messages from the queue
                gotSomeMessages = false;

                // Get a batch of messages
                IEnumerable <CloudQueueMessage> messages = await _queue.GetMessagesAsync(MessagesPerGet, cancellationToken).ConfigureAwait(false);

                foreach (CloudQueueMessage message in messages)
                {
                    // Check for cancellation before processing a message
                    cancellationToken.ThrowIfCancellationRequested();

                    // We obviously got some messages since we're processing one
                    gotSomeMessages = true;

                    // Try to deserialize the message to an EncodingJobEvent
                    EncodingJobEvent jobEvent = null;
                    try
                    {
                        var settings = new JsonSerializerSettings {
                            DateTimeZoneHandling = DateTimeZoneHandling.Utc
                        };
                        jobEvent = JsonConvert.DeserializeObject <EncodingJobEvent>(message.AsString, settings);
                    }
                    catch (Exception e)
                    {
                        Logger.Warning(e, "Exception while deserializing event, message will be deleted");
                    }

                    // If there was a problem with deserialization, just assume a poison message and delete it
                    if (jobEvent == null)
                    {
                        await _queue.DeleteMessageAsync(message, cancellationToken).ConfigureAwait(false);

                        continue;
                    }

                    // Ignore any messages that aren't for JobStateChanges
                    if (jobEvent.IsJobStateChangeEvent() == false)
                    {
                        await _queue.DeleteMessageAsync(message, cancellationToken).ConfigureAwait(false);

                        continue;
                    }

                    // Otherwise, handle the event
                    bool handledSuccessfully = false;
                    try
                    {
                        await HandleEncodingJobEvent(jobEvent).ConfigureAwait(false);

                        handledSuccessfully = true;
                    }
                    catch (Exception e)
                    {
                        Logger.Error(e, "Error while handling JobStateChanged message");
                    }

                    // If the message was handled successfully, just delete it
                    if (handledSuccessfully)
                    {
                        await _queue.DeleteMessageAsync(message, cancellationToken).ConfigureAwait(false);

                        continue;
                    }

                    // If the message is over the number of retries, consider it a poison message, log it and delete it
                    if (jobEvent.RetryAttempts >= MaxRetries)
                    {
                        // Move the message to a poison queue (NOTE: because Add + Delete aren't "transactional" it is possible
                        // a poison message might get added more than once to the poison queue, but that's OK)
                        Logger.Fatal("Giving up on message: {Message}", message.AsString);
                        await _poisonQueue.AddMessageAsync(message, cancellationToken).ConfigureAwait(false);

                        await _queue.DeleteMessageAsync(message, cancellationToken).ConfigureAwait(false);

                        continue;
                    }

                    // Increment the retry attempts and then modify the message in place so it will be processed again
                    int secondsUntilRetry = (2 ^ jobEvent.RetryAttempts) * 10;
                    jobEvent.RetryAttempts++;
                    message.SetMessageContent(JsonConvert.SerializeObject(jobEvent));
                    await _queue.UpdateMessageAsync(message, TimeSpan.FromSeconds(secondsUntilRetry),
                                                    MessageUpdateFields.Content | MessageUpdateFields.Visibility, cancellationToken).ConfigureAwait(false);
                }

                // If we got some messages from the queue, keep processing until we don't get any
            } while (gotSomeMessages);

            // Exit method to allow a cooldown period (10s) between polling the queue whenever we run out of messages
        }
Пример #25
0
        private static async Task Main(string[] args)
        {
            var exitCode = 0;

            try
            {
                BindConfigurationOptions();
                ConfigureServices();
                ConfigureLogging();

                logger.Information("Starting {applicationTitle}...", ApplicationTitle);

                var serviceProvider        = services.BuildServiceProvider();
                var practicePlanRepository = serviceProvider.GetService <IPracticePlanRepository>();

                DateTimeOffset startDate    = new DateTimeOffset(2018, 9, 25, 0, 0, 0, 0, new TimeSpan());
                var            practicePlan = new PracticePlanDto {
                    StartDate = startDate
                };

                logger.Information("Upserting practice plan with start date {startDate:yyyy-MM-dd}", practicePlan.StartDate);
                await practicePlanRepository.UpsertAsync(practicePlan);

                var fetchedPlan = await practicePlanRepository.GetAsync(startDate);

                logger.Information("Fetched practice plan with start date {startDate:yyyy-MM-dd}", fetchedPlan.StartDate);

                fetchedPlan.StartDate = startDate.AddDays(1);
                logger.Information("Updating the start date to {startDate:yyyy-MM-dd}", fetchedPlan.StartDate);
                await practicePlanRepository.UpsertAsync(fetchedPlan);

                fetchedPlan = await practicePlanRepository.GetAsync(fetchedPlan.StartDate);

                logger.Information("Fetched updated practice plan with start date {startDate:yyyy-MM-dd}", fetchedPlan.StartDate);

                var planToDelete = new PracticePlanDto {
                    StartDate = startDate
                };
                logger.Information("Deleting the plan with start date {startDate:yyyy-MM-dd}", planToDelete.StartDate);
                await practicePlanRepository.DeleteAsync(planToDelete);

                fetchedPlan = await practicePlanRepository.GetAsync(startDate);

                if (fetchedPlan == null)
                {
                    logger.Information("No practice plan exists with start date {startDate:yyyy-MM-dd}", startDate);
                }
                else
                {
                    logger.Information("Fetched practice plan with start date {startDate:yyyy-MM-dd}", fetchedPlan.StartDate);
                }
            }
            catch (Exception ex)
            {
                logger.Fatal(ex, "An unhandled exception has occurred!");
                exitCode = -1;
            }

            logger.Information("Exiting {applicationTitle} with exit code {exitCode}...", ApplicationTitle, exitCode);
            Log.CloseAndFlush();

            Environment.Exit(exitCode);
        }
Пример #26
0
 public void Fatal <T>(string stringTemplate, T payload = default)
 {
     _logger.Fatal <T>(stringTemplate, payload);
 }
Пример #27
0
 public void Fatal(string message) => _logger.Fatal($"[{_loggerName}] {message}");
Пример #28
0
 public void Fatal(string message)
 {
     log.Fatal(message);
 }