public string Download(string addr) { try { logger?.Verbose("download " + addr); lock (wc) { var result = wc.DownloadString(addr); logger?.Verbose("download complete: " + addr); return(result); } } catch (WebException we) { logger?.Error(we, "Error downloading from " + addr); var rs = we.Response?.GetResponseStream(); if (rs != null) { var err = new StreamReader(rs).ReadToEnd(); logger?.Error(we, "Error downloading from " + addr + ". Response: " + err); } throw; } catch (Exception e) { logger?.Error(e, "Error downloading from " + addr); throw; } }
public void LoggingToFile() { //string relativePath = Path.Combine(Environment.CurrentDirectory, "log.txt"); string absolutePath = "C:/logi/log.txt"; var logConfiguration = new LoggerConfiguration(); logConfiguration .WriteTo.File(absolutePath, Serilog.Events.LogEventLevel.Debug) .WriteTo.Console(new CompactJsonFormatter()); Serilog.Core.Logger logger = logConfiguration.CreateLogger(); logger.Debug("to się nie zaloguje, bo minimalnym poziomem jest Information"); logger.Error("błąd!"); try { throw new Exception("can't find the author!"); } catch (Exception e) { logger.Error(e, "operacja zwróciła wyjątek"); } }
/// <summary> /// Reads the XML from the stream and configures the message factory with its values. /// </summary> /// <returns></returns> /// <param name="mfact">The message factory to be configured with the values read from the XML.</param> /// <param name="source">The InputSource containing the XML configuration</param> /// <typeparam name="T"></typeparam> private static void Parse <T>(MessageFactory <T> mfact, Stream source) where T : IsoMessage { try { var xmlDoc = new XmlDocument(); xmlDoc.Load(source); var root = xmlDoc.DocumentElement; if (root == null || !root.Name.Equals("n8583-config")) { throw new Exception("Invalid ISO8583 config file. XML file does not contain any root element."); } ParseHeaders(root.GetElementsByTagName("header"), mfact); ParseTemplates(root.GetElementsByTagName("template"), mfact); //Read the parsing guides ParseGuides(root.GetElementsByTagName("parse"), mfact); } catch (Exception e) { logger.Error($"ISO8583 Cannot parse XML configuration {e}"); } }
public void Execute() { try { //init object IRepository _InputRepository = new InputRepository(); if (_InputRepository.HasFiles()) { OutputRepository _outputRepository = new OutputRepository(); //Get files from path FileInfo[] files = _InputRepository.GetAll(); //Extract information by each one Parallel.ForEach(files, item => { OutputFileContent outputFileContent = null; try { //try parse files outputFileContent = AnalyzeFile(item); } catch (Exception ex) { //Move to rejected folder if has error to parse _InputRepository.RejectFile(item); _logger.Error(ex, $"The file {item.Name} cannot be converted and has been moved to the rejected folder."); //move to next interaction return; } //log the processed information _logger.Information($"Processed file {item.FullName} output: {Serializer.Serialize(outputFileContent)}"); //Save file in output diretory _outputRepository.AddFile(outputFileContent); //create backup _InputRepository.BackupFile(item.FullName); //delete from input folder _InputRepository.DeleteFile(item.FullName); }); } } catch (IOException ex) { _logger.Error(ex, "An I/O error is ocurred"); } catch (Exception ex) { _logger.Error(ex, "An error is ocurred"); } }
public void LogError(string message, Exception exception = null, params object[] propertyValues) { if (exception != null) { _logger.Error(exception, message, propertyValues); } else { _logger.Error(message); } }
public void Error(string message, Exception ex = null) { if (ex == null) { logger.Error(message); } else { logger.Error(ex, message); } }
public void Processar(string token) { try { log.Information("Inicio da sincronização de produtos"); CarregarSerializado(); var alterados = new List <Produto>(); log.Information("Buscando produtos..."); var produtos = BuscarProdutos(); log.Information("Quantidade de produtos encontrados: " + produtos.Count()); if (produtoAnterior is not null) { log.Debug("Existe produto anterior... "); // log.Information("Vou comparar lista..."); Parallel.ForEach(produtos, prod => { if (produtoAnterior.ContainsKey(prod.CodigoProduto)) { if (!prod.Equals(produtoAnterior[prod.CodigoProduto])) { log.Information("Esse produto foi alterado: " + prod.CodigoProduto + " " + prod.NomeProduto); prod.Novo = 0; alterados.Add(prod); } } else { log.Information("Este é um produto novo..: " + prod.CodigoProduto + " " + prod.NomeProduto); prod.Novo = 1; alterados.Add(prod); } }); AtualizarNuvem(alterados, token); } produtoAnterior = ConverterEmDicionario(produtos); using var arquivo = new FileStream(ARQUIVO_SERIALIZADO, FileMode.OpenOrCreate); var formatter = new BinaryFormatter(); // log.Information("Serializando os produtos....."); formatter.Serialize(arquivo, produtoAnterior); log.Information("Sincronização de produtos finalizada!"); } catch (Exception e) { log.Error("Erro: " + e.Message); throw; } }
public void AtualizarNuvem(List <ClassEstoque> produtos, string token) { EnvReader envReader = new EnvReader(); // var http = new HttpClient(); log.Information("Verificando se preciso atualizar o estoque na nuvem... "); foreach (var p in produtos) { log.Information("Codigo Estoque: " + p.CodigoEstoque + " Produto: " + p.CodigoProduto); var jjjhonson = new { id_loja = p.CodigoEmpresa, codigo_produto = p.CodigoProduto, codigo_barras = p.CodigoBarra, qtd_estoque = p.Estoque, preco_venda = p.PrecoVenda, preco_promocao = p.PrecoPromocao, fabricante = p.Fabricante, status = p.Ativo, }; var client = new RestClient(envReader.GetStringValue("API")); RestRequest request; if (p.Novo == 0) { log.Information("Alterar estoque: " + jjjhonson.ToString()); request = new RestRequest($@"/estoque/{p.CodigoEmpresa}/{p.CodigoProduto}", Method.PUT); } else { log.Information("Adicionar estoque: " + jjjhonson.ToString()); request = new RestRequest("/estoque/", Method.POST); } request.AddHeader("auth", token); request.AddJsonBody(jjjhonson); var resposta = client.Execute(request); if (resposta.StatusCode != System.Net.HttpStatusCode.Created && resposta.StatusCode != System.Net.HttpStatusCode.OK) { log.Error("Não atualizei o estoque: "); log.Error(resposta.Content); throw new Exception(resposta.Content); } } }
public void Run() { Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); try { _initialize(); _logger.Information(string.Format("{0} Action Starting ...", _activityName)); _keepRunning = true; while (_keepRunning) { _runner(); Thread.Sleep(WorkerLoopTimeSleeping); } } catch (Exception ex) { _logger.Error(ex, "An Error occurred : {0}", ex.Message); _error(); throw; } finally { stopwatch.Stop(); _cleaning(); _logger.Information(string.Format("{0} Action Completed in {1}", _activityName, Utils.ElapsedTime(stopwatch.Elapsed))); } }
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); } }
public void Error(Exception ex, string messageTemplate) { if (IsConfigured) { _log.Error(ex, messageTemplate); } }
public void Run(string name, Action <WebClientBase> a) { Thread t = new Thread(new ThreadStart(() => { int number = taskCount++; logger.Verbose($"Start thread {name} [{number}]"); lock (locker) { try { logger.Verbose($"Execution begin {name} [{number}]"); using (wc = new WebClientBase(logger)) a(wc); logger.Verbose($"Execution end {name} [{number}]"); } catch (Exception e) { logger.Error(e, $"Exection failed: {name} [{number}]"); OnError?.Invoke($"{name} [{number}]", new ErrorEventArgs(e)); } } })); t.Start(); }
private void btnSend_Click(object sender, EventArgs e) { try { SendMail(txtSubject.Text, txtTo.Text, webBody.DocumentText, txtFrom.Text, comboServerName.Text, txtPort.Text, chkRequiredSSL.Checked, txtUserName.Text, txtPassword.Text, attachFile); // log information if (attachFile != null && attachFile.Trim().Length > 0) { log.Information("Email sending success to " + txtTo.Text + " with attach file " + attachFile); } else { log.Information("Email sending success to " + txtTo.Text + " without attachment."); } MessageBox.Show("Email send out ready! Check in your inbox " + txtTo.Text, "Success", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception ex) { log.Error(ex, "Error"); MessageBox.Show("Email sending Fail! Check error in the log file.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public void Error(Exception ex, string messageTemplate) { if (messageTemplate == null) { messageTemplate = $"Parent: {System.Reflection.Assembly.GetEntryAssembly()?.GetName().Name}"; } else { messageTemplate += $", Parent: {System.Reflection.Assembly.GetEntryAssembly()?.GetName().Name}"; } if (IsConfigured) { _log.Error(ex, messageTemplate); } }
public void JsonLogging() { var logConfiguration = new LoggerConfiguration(); logConfiguration.WriteTo.Console(new CompactJsonFormatter()); Serilog.Core.Logger logger = logConfiguration.CreateLogger(); int ticksElapsed = 123456; Log.Information($"String interpolation: Dodawanie autora zajęło {ticksElapsed} sekund."); // źle! Serilog nie rozpozna parametru Log.Information("Poprawne formatowanie: Dodawanie autora zajęło {ticksElapsed} sekund.", ticksElapsed); try { throw new Exception("can't find the author!"); } catch (Exception e) { logger.Error(e, "operacja zwróciła wyjątek"); } var złożonyObiekt = new { PierwszePole = 123, DrugiePole = "21314235" }; logger.Information("Mój złożony obiekt:{obiekt}", złożonyObiekt); // źle! brak małpy - obiekt będzie stringiem zawierającym JSON, a nie JSON-em logger.Information("Mój złożony obiekt:{@obiekt}", złożonyObiekt); var liczby = new[] { 1, 2, 3 }; logger.Information("Liczby:{@liczby}", liczby); }
private static async Task <bool> SendMessageToRetryTopic(EmailMessage message, bool addTime = false) { try { var config = new ProducerConfig { BootstrapServers = Constants.BootstrapServers }; using (var producer = new ProducerBuilder <Null, string>(config).Build()) { if (addTime) { message.Timestamp = message.Timestamp.AddSeconds(20); message.Attempts += 1; } var result = await producer.ProduceAsync( Constants.TopicName, new Message <Null, string> { Value = JsonConvert.SerializeObject(message) } ); return(result.Status == PersistenceStatus.Persisted); } } catch (Exception ex) { _logger.Error($"Erro ao realizar o retry. \nMensagem : {message.ToString()} \nErro:{ex.Message}"); } return(false); }
public void BasicLogging() { var logConfiguration = new LoggerConfiguration(); logConfiguration.WriteTo.Console(restrictedToMinimumLevel: Serilog.Events.LogEventLevel.Information); Serilog.Core.Logger logger = logConfiguration.CreateLogger(); logger.Debug("to się nie zaloguje, bo minimalnym poziomem jest Information"); logger.Error("błąd!"); try { throw new Exception("can't find the author!"); } catch (Exception e) { logger.Error(e, "operacja zwróciła wyjątek"); } }
public async Task PublishError(string identifier, ExceptionItem exceptionItem) { try { await Task.Run(() => { _logger.Error(string.Format(Constant.LoggingFormat, identifier, exceptionItem.Message), JsonConvert.SerializeObject(exceptionItem)); }); } catch (Exception) { } }
public void Error(Exception ex, string messageTemplate) { if (messageTemplate == null) { messageTemplate = $"Parent: {System.Reflection.Assembly.GetEntryAssembly()?.GetName().Name}"; } else { messageTemplate += $", Parent: {System.Reflection.Assembly.GetEntryAssembly()?.GetName().Name}"; } if (IsConfigured) { _log.Error(ex, messageTemplate); } #if DEBUG Debug.WriteLine($"***********************************\nThrow an exception : {ex.Message}\n{messageTemplate}\n{ex.StackTrace}***********************************\n"); #endif }
private static void LogException(string message) { // Create logger if (_loggerError == null) { var loggerConfig = CreateLoggerConfiguration(Category.Error, LogFolderPath, $"ex_{_prefixLogName}_.txt"); _loggerError = loggerConfig.CreateLogger(); } // Log _loggerError.Error(message); }
public Logger(IConfiguration configuration) { var LogFileName = configuration["LogFileName"] ?? "log-{Date}.log"; _logger = new Serilog.LoggerConfiguration() .MinimumLevel.Debug() .WriteTo.RollingFile(Path.Combine(Environment.CurrentDirectory, LogFileName)) .CreateLogger(); if (configuration["LogFileName"] == null) { _logger.Error("\"PartyCli.AppSettings.json\" section LogFileName not found. Using default name \"log-{Date}.log\""); } }
static async Task Main(string[] args) { log.Error("Starting"); ping = new Ping(); timerSchedule = 1000; jobbTimer = new System.Timers.Timer(timerSchedule); jobbTimer.Elapsed += ExicuteQueWork; jobbTimer.AutoReset = false; jobbTimer.Start(); while (true) { //Keep program } log.Debug("close program"); }
public IActionResult Index() { //ILogger _logger.BeginScope("User: {username}", User.Identity?.Name); _logger.LogInformation("Hey! I'm in the Index!"); try { for (int i = 0; i < 10; i++) { _logger.LogInformation("For loop... {i}", i); if (i == 5) { throw new Exception("ups!"); } } } catch (Exception e) { _logger.LogError(e, "Strange... something broke"); } //Serilog _myLogger.ForContext("User", User.Identity?.Name); _myLogger.Information("User: {username}", User.Identity?.Name); try { for (int i = 0; i < 10; i++) { _myLogger.Information("For loop... {i}", i); if (i == 5) { throw new Exception("ups!"); } } } catch (Exception e) { _myLogger.Error(e, "Strange... something broke"); } return(View()); }
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); } } }
static async Task Main(string[] args) { _logger = Core.Logger.Logger.BuildLogger(); _logger.Information("Envio de mensagens com o Kafka"); try { //await CreateTopicsAndPartitions(); if (int.TryParse(args.Length > 0 ? args[0] : "1", out int quantity)) { await SendMessages(quantity); } } catch (Exception ex) { _logger.Error($"Erro principal: {ex.Message}"); } }
public static async Task <Result> CreateJsonFile() { string FileName = _userName + "_data.json"; Result result = new Result(); result.IsDbCreated = false; result.CreatedFileName = FileName; if (await isFilePresent(FileName) == false) { StorageFolder localFolder = ApplicationData.Current.LocalFolder; await localFolder.CreateFileAsync(FileName, CreationCollisionOption.ReplaceExisting); //write data in file try { _logger.Information("Creating DB For user " + FileName); StorageFile myFile = await localFolder.GetFileAsync(FileName); //string initialJsonString = await FileIO.ReadTextAsync(await StorageFile.GetFileFromApplicationUriAsync(new Uri(@"ms-appx:///JsonInitialDb//UserData.json"))); string initialJsonString = await FileIO.ReadTextAsync(await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///JsonInitialDb//UserData.json"))); await FileIO.WriteTextAsync(myFile, initialJsonString); result.IsDbCreated = true; _logger.Information("DB Created!!!!!!!!"); } catch (Exception e) { _logger.Error("Failure: " + e.Message); result.IsDbCreated = false; } } else { _logger.Information(FileName + "is already there "); } return(result); }
public static void HandleError(Exception t) { if (IsRunningOnBuildServer()) { Log.Error(t, "Full error information:"); } if (IsExpectedError(t)) { DisplayErrorMessage(t); } else { DisplayUnexpectedErrorMessage(t); } }
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(); }
private static async Task SendMessages(int quantity) { var rnd = new Random(); var config = new ProducerConfig { BootstrapServers = Constants.BootstrapServers }; using (var producer = new ProducerBuilder <Null, string>(config) .SetErrorHandler((_, error) => _logger.Error($"Erro: {error}")) .Build()) { for (int i = 0; i < quantity; i++) { var mailMessage = new EmailMessage { Message = $"Mensagem de teste: {rnd.Next()}", Timestamp = DateTime.Now.AddSeconds(10) }; var result = await producer.ProduceAsync( Constants.TopicName, new Message <Null, string> { Value = JsonConvert.SerializeObject(mailMessage) } ); //var result = await producer.ProduceAsync // (new TopicPartition(Constants.TopicName, new Partition(i)), // new Message<Null, string> { Value = message }); _logger.Information($"Mensagem: {mailMessage.ToString()} - Status: {result.Status.ToString()} / Topic/Partition: {result.TopicPartition.Topic}/{result.TopicPartition.Partition} "); } producer.Flush(TimeSpan.FromSeconds(6)); _logger.Information($" {quantity} mensagens produzidas."); } }
public async static void SetDefaultData() { //data stored in json as a content can not be edited in uwp ie read only //so i need to push this data in application data container which is allowed to read as well as write //string jsonString = await FileIO.ReadTextAsync(await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///DB//UserData.json"))); // string jsonStrings = await FileIO.ReadTextAsync(await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets//UserData.json"))); //working fine _minderLogger.Information("$$$$$$$$$$$$$$$$$$$$$$$ Setting Default data for " + _containerName + " $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$"); string jsonString = await FileIO.ReadTextAsync(await ApplicationData.Current.LocalFolder.GetFileAsync("UserData.json")); var rootObject = JsonObject.Parse(jsonString); //newContainer.Values["UserData"] = rootObject.ToString(); try { _minderLogger.Information(jsonString); _localSettings.Containers[_containerName].Values["UserData"] = jsonString; //_localSettings.Values[_containerName] = jsonString; _minderLogger.Information("$$$$$$$$$$$$$$$$ Default Data Created $$$$$$$$$$$$$$$"); } catch (Exception ex) { _minderLogger.Error("Error while setting default data" + ex.StackTrace); } }