public static void SetupLogging(string filePath)
        {
            if (_logger == null)
            {
                if (filePath == null)
                {
                    _logger = new LoggerConfiguration()
                              .MinimumLevel.Debug()
                              .WriteTo.Console()
                              .CreateLogger();
                    _logger.Information("Creating Console Logger");
                }
                else
                {
                    _logger = new LoggerConfiguration()
                              .MinimumLevel.Debug()
                              .WriteTo.Console()
                              .WriteTo.File(filePath, rollingInterval: RollingInterval.Day)
                              .CreateLogger();

                    _logger.Information("Creating File Logger");
                }
            }
            else
            {
                _logger.Warning("SetupLogging called twice - Not recreating Logger!");
            }
        }
示例#2
0
 public void Warn <T1>(string message, T1 arg1)
 {
     if (shouldLog())
     {
         sLog.Warning(makeMessage(message), arg1);
     }
 }
示例#3
0
        public void LogMessage(LogLevel logLevel, string message)
        {
            switch (logLevel)
            {
            case LogLevel.Critical:
                _logger.Fatal(message);
                LogReceived?.Invoke(LogEventLevel.Fatal, _logger, message, _application);
                break;

            case LogLevel.Debug:
                _logger.Debug(message);
                LogReceived?.Invoke(LogEventLevel.Debug, _logger, message, _application);
                break;

            case LogLevel.Information:
                _logger.Information(message);
                LogReceived?.Invoke(LogEventLevel.Information, _logger, message, _application);
                break;

            case LogLevel.Warning:
                _logger.Warning(message);
                LogReceived?.Invoke(LogEventLevel.Warning, _logger, message, _application);
                break;

            case LogLevel.Error:
                _logger.Error(message);
                LogReceived?.Invoke(LogEventLevel.Error, _logger, message, _application);
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(logLevel), logLevel, null);
            }
        }
示例#4
0
 /// <summary>
 ///     Configures a MessageFactory using the configuration file at the path specified (will be searched
 ///     from the application domain
 /// </summary>
 /// <param name="mfact">The message factory to be configured with the values read from the XML.</param>
 /// <param name="path">Path.</param>
 /// <typeparam name="T"></typeparam>
 public static void ConfigureFromClasspathConfig <T>(MessageFactory <T> mfact,
                                                     string path) where T : IsoMessage
 {
     try
     {
         var f = AppDomain.CurrentDomain.BaseDirectory + path;
         using (var fsSource = new FileStream(f,
                                              FileMode.Open,
                                              FileAccess.Read))
         {
             logger.Debug("ISO8583 Parsing config from classpath file {Path}",
                          path);
             Parse(mfact,
                   fsSource);
         }
     }
     catch (FileNotFoundException)
     {
         logger.Warning("ISO8583 File not found in classpath: {Path}",
                        path);
     }
 }
示例#5
0
        public MainServerLoop(Serilog.Core.Logger log)
        {
            if (!File.Exists("./Settings.ini"))
            {
                Console.WriteLine("Nie znaleziono pliku Settings.ini, zostanie on wygenerowany automatycznie.");
                log.Warning("Couldn't find Settings.ini, generating file...");
                using (StreamWriter sw = new StreamWriter("./Settings.ini"))
                {
                    sw.WriteLine("ServerAddress: 127.0.0.1");
                    sw.WriteLine("ServerPort: 7000");
                    sw.WriteLine("ConnectionString: ");
                }
                log.Warning("Settings.ini created.");
            }
            if (File.Exists("./Settings.ini"))
            {
                log.Information("Loading settings...");
                using (StreamReader sr = new StreamReader("./Settings.ini"))
                {
                    while (!sr.EndOfStream)
                    {
                        try
                        {
                            string[] entries = sr.ReadLine().Split(':');
                            Settings.Properties.Add(entries[0].Trim(), entries[1].Trim());
                        }
                        catch (Exception ex)
                        {
                            log.Error($"{ex.Message}, {ex.InnerException}");
                            return;
                        }
                    }
                }
            }

            _server = new Server(int.Parse(Settings.Properties[FieldTypes.ServerPort.ToString()]), Settings.Properties[FieldTypes.ServerAddress.ToString()], log);
            _server.StartListening();
        }
示例#6
0
 private static void WriteError(Exception error)
 {
     try
     {
         var saveFolder = PlatformUtilities.AppDataFolder();
         var saveFile   = Path.Combine(saveFolder, ErrorLogFileName);
         File.WriteAllText(saveFile, error.ToString());
     }
     catch (Exception t)
     {
         Log.Warning(t, "Failed to log error.");
         Log.Error(error, "Original error.");
     }
 }
示例#7
0
        public async Task Watch(CancellationToken cancellationToken)
        {
            string resourceVersion = null;

            while (!cancellationToken.IsCancellationRequested)
            {
                try
                {
                    var listTask = Client.ListPodForAllNamespacesWithHttpMessagesAsync(
                        allowWatchBookmarks: true,
                        watch: true,
                        resourceVersion: resourceVersion,
                        cancellationToken: cancellationToken
                        );
                    var tcs = new TaskCompletionSource();
                    using var watcher = listTask.Watch <V1Pod, V1PodList>(
                              (type, pod) => {
                        resourceVersion = pod.ResourceVersion();
                        HandlePodEvent(type, pod);
                    },
                              (err) =>
                    {
                        Logger.Error(err, "Handling error event for pod watch stream.");
                        if (err is KubernetesException kubernetesError)
                        {
                            // Handle "too old resource version"
                            if (string.Equals(kubernetesError.Status.Reason, "Expired", StringComparison.Ordinal))
                            {
                                resourceVersion = null;
                            }
                        }
                        tcs.TrySetException(err);
                        throw err;
                    },
                              () => {
                        Logger.Warning("Pod watch has closed.");
                        tcs.TrySetResult();
                    }
                              );
                    using var registration = cancellationToken.Register(watcher.Dispose);
                    await tcs.Task;
                }
                catch (Exception ex)
                {
                    Log.Error(ex, "Error with pod watch stream.");
                    await Task.Delay(1000, cancellationToken);
                }
            }
        }
示例#8
0
 /// <inheritdoc />
 public void Warning(string messageTemplate)
 {
     _log.Warning(messageTemplate);
 }
示例#9
0
 public override void onConnectionLost(string clientAdress, Exception exception)
 {
     base.onConnectionLost(clientAdress, exception);
     _log.Warning($"Client: {clientAdress}, lost connection because {exception.Message}, {exception.InnerException}");
 }
示例#10
0
 public void Warning(string message)
 {
     log.Warning(message);
 }
示例#11
0
        static async Task Main(string[] args)
        {
            _logger = Core.Logger.Logger.BuildLogger();

            var cts = new CancellationTokenSource();

            _logger.Information("Consumindo mensagens do Kafka");

            Console.CancelKeyPress += (_, e) =>
            {
                e.Cancel = true;
                cts.Cancel();
            };

            var config = new ConsumerConfig
            {
                BootstrapServers      = Constants.BootstrapServers,
                GroupId               = Constants.GroupId,
                AutoOffsetReset       = AutoOffsetReset.Earliest,
                Acks                  = Acks.All,
                EnableAutoCommit      = true,
                EnableAutoOffsetStore = false
            };


            try
            {
                using (var consumer = new ConsumerBuilder <Ignore, string>(config)
                                      .SetStatisticsHandler((_, json) => _logger.Information($"Statistic: {json}"))
                                      .SetLogHandler((_, log) => _logger.Information($"Log: {log}"))
                                      .Build())
                {
                    consumer.Subscribe(Constants.TopicName);


                    try
                    {
                        while (true)
                        {
                            var commitMessage = true;
                            var cr            = consumer.Consume(cts.Token);

                            var message = JsonConvert.DeserializeObject <EmailMessage>(cr.Message.Value);

                            var topicPartitions = new List <TopicPartition>()
                            {
                                { cr.TopicPartition }
                            };

                            try
                            {
                                var now = DateTime.Now;

                                _logger.Information($"===========================================================");
                                _logger.Information($"Hora atual: {now}");

                                if (DateTime.Compare(now, message.Timestamp) == -1)
                                {
                                    var waitTime = ((TimeSpan)(message.Timestamp - now)).TotalMilliseconds;

                                    _logger.Warning($"Hora que deve processar: {message.Timestamp}. Esperar: {waitTime} ms");

                                    consumer.Pause(topicPartitions);

                                    await Task.Delay(TimeSpan.FromMilliseconds(waitTime));

                                    consumer.Resume(topicPartitions);

                                    //commitMessage = await SendMessageToRetryTopic(message);
                                }

                                await ProcessMessage(message);
                            }
                            catch (MyKafkaException kex)
                            {
                                _logger.Error($"Erro interno: {kex.Message}");
                                _logger.Information("Enviando para retry topic.");
                                commitMessage = await SendMessageToRetryTopic(message, true);
                            }
                            finally
                            {
                                if (commitMessage)
                                {
                                    consumer.StoreOffset(cr);
                                    _logger.Information($"Mensagem '{message.Id}' commitada.");

                                    //consumer.Pause(topicPartitions);
                                    //_logger.Information($"Consumer paused. {cr.TopicPartition.Topic} / {cr.TopicPartition.Partition}");

                                    //await Task.Delay(TimeSpan.FromSeconds(10));

                                    //consumer.Resume(topicPartitions);
                                    //_logger.Information($"Consumer resumed. {cr.TopicPartition.Topic} / {cr.TopicPartition.Partition}");
                                }
                            }
                        }
                    }
                    catch (OperationCanceledException)
                    {
                        consumer.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Error($"Erro: {ex.Message}");
            }
        }
示例#12
0
 public void Warn(string message)
 {
     ThreadSafeExecute(() => _serilog.Warning(message));
 }
示例#13
0
 public void LogWarning(string message, params object[] args)
 {
     _logger.Warning(message, args);
 }
示例#14
0
 public void Warning(string messageTemplate, [CallerFilePath] string callerPath = "", [CallerLineNumber] long callerLine = 0, [CallerMemberName] string callerMember = "")
 {
     _logger.Warning(BuildMessage(messageTemplate, callerPath, callerLine, callerMember));
 }
示例#15
0
 public void Warn()
 {
     internalLogger.Warning(string.Empty);
 }
示例#16
0
 /// <summary>
 /// Used to log warning information for a system
 /// </summary>
 /// <param name="messageTemplate"></param>
 /// <param name="propertyValues"></param>
 public static void Warn(string messageTemplate)
 {
     log.Warning(messageTemplate);
 }
示例#17
0
 public void Warn(LogModel logModel)
 {
     _serilogLogger.Warning(JsonConvert.SerializeObject(logModel));
 }
示例#18
0
        static void Main(string[] args)
        {
            int nsecs = 1000;

            try
            {
                var configuration = new ConfigurationBuilder()
                                    .SetBasePath(Directory.GetCurrentDirectory())
                                    .AddJsonFile("appsettings.json")
                                    .Build();
                config = configuration;

                //var configuration = builder.Build();
                // config = new ConfigurationBuilder()
                //     .AddJsonFile("appsettings.json", true, true)
                //     .Build();
//Serilog.Debugging.SelfLog.Enable(msg => Debug.WriteLine(msg));
//Serilog.Debugging.SelfLog.Enable(Console.Error);

// File logger

/*
 *          var Log = new LoggerConfiguration()
 *              //.MinimumLevel.Information()
 *              //.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
 *              .Enrich.FromLogContext()
 *              //.WriteTo.Console()
 *              //.WriteTo.RollingFile("log-{Date}.txt") //, fileSizeLimitBytes: 123)
 *              .ReadFrom.Configuration(configuration)
 *              //.ReadFrom.Configuration(config)
 *              //.Enrich.FromLogContext()
 *              .CreateLogger();
 */
/*
 *         var Log = new LoggerConfiguration()
 *         .WriteTo.SumoLogic("https://endpoint4.collection.us2.sumologic.com/receiver/v1/http/ZaVnC4dhaV1OJMaHi0tURR0qnAZ2G4CmmLdC4MdjYUbmtlFDnp5jAd9h4z0AbkVsIYNHswsCLX87SsDb9hZsW_aY6umdGIQOjPoNMeoUflRQlGL4q6LYVQ==")
 *             //.WriteTo.SumoLogic("http://localhost", textFormatter: new MessageTemplateTextFormatter("FOOBAR", null))
 *             .WriteTo.MongoDBCapped()
 *             .CreateLogger();
 */
                // From appsettings.json

                Log = new LoggerConfiguration()
                      .ReadFrom.Configuration(configuration)
                      .CreateLogger();

                /**
                 * var Log = new LoggerConfiguration()
                 * //.WriteTo.MongoDB("mongodb://mymongodb/logs")
                 * .WriteTo.MongoDB("mongodb://localhost:27017/logs")
                 * //.WriteTo.MongoDBCapped("mongodb://localhost:27017/logs", cappedMaxSizeMb: 50, cappedMaxDocuments: 7)
                 * .MinimumLevel.Verbose()
                 * //.MinimumLevel.Fatal()
                 * .CreateLogger();
                 **/

                //Console.WriteLine("The current time is " + DateTime.Now);
                showVitals();

                listStudents();
                ListCollectionAsync().Wait();

                //Console.ReadLine();
                Log.Verbose("VVVVVVVV Verbose");

                Console.WriteLine($"'waiting {nsecs} milli secs."); Task.Delay(nsecs).Wait(); // Wait 2 seconds with blocking
                Log.Debug("DDDDDDDD Debug");
                Console.WriteLine($"'waiting {nsecs} milli secs."); Task.Delay(nsecs).Wait(); // Wait 2 seconds with blocking
                Log.Information("IIIIIIII Information");
                Console.WriteLine($"'waiting {nsecs} milli secs."); Task.Delay(nsecs).Wait(); // Wait 2 seconds with blocking
                Log.Warning("WWWWWWWW Warning");
                Log.Fatal("FFFFFFFF Fatal terminated unexpectedly");
                Log.Error("EEEEEEEE Error");
                Log.Verbose("VVVVVVVV Error");


                Log.Information("Host IIIIIIIIIIII");
                nsecs = 6000;
                Console.WriteLine($"'waiting {nsecs} milli secs. The end is near."); Task.Delay(nsecs).Wait(); // Wait 2 seconds with blocking
            }
            catch (Exception ex)
            {
                Console.WriteLine($"\n\n catch catch\n{ex}");
                if (Log != null)
                {
                    Log.Fatal($"catch catch\n {ex}");
                }
                //return;
            }
            finally
            {
                if (Log != null)
                {
                    Log.Information("Fulsh");
                }
                //Log.Information("Fulsh");
                //Log.CloseAndFlush();
            }

            Console.WriteLine($"'waiting {nsecs} milli secs. The end is near."); Task.Delay(nsecs).Wait(); // Wait 2 seconds with blocking
        }
示例#19
0
 public void Warn(string info)
 {
     _logger.Warning(info);
 }
示例#20
0
 public void Warning(string message, params object[] propertyValues)
 {
     Log.Warning(message, propertyValues);
 }
示例#21
0
 public void Warning <T>(Exception exception, string messageTemplate, T propertyValue)
 {
     log.Warning(exception, messageTemplate, propertyValue);
 }
示例#22
0
 public void Warning(string messageTemplate, params object[] parameters)
 {
     _logger.Warning(messageTemplate, parameters);
 }
示例#23
0
 public static void Warning(string msg)
 {
     seriLog.Warning(msg);
 }
示例#24
0
 public void LogWarning(Exception ex, [CallerMemberName] string caller = null)
 => _logger.Warning($"Caller: {caller}"
                    + Environment.NewLine
                    + Environment.NewLine
                    + ex.ToString());
示例#25
0
 public void LogWarning(string message)
 {
     _logger.Warning(message);
 }
示例#26
0
 public static void Warning(string message)
 {
     _logger.Warning(message);
 }