private static async Task Main(string[] args) { await BootStrapper.Run <Empty>(args, startUp : async(sp, so) => { var logger = new LoggerConfiguration() .WriteTo.Console(outputTemplate: "{Message:lj}{NewLine}{Exception}") .WriteTo.File("Test.log").CreateLogger(); try { Console.Title = "Event Delivery Test"; Console.WriteLine("---Welcome To Event Delivery Test---"); Console.WriteLine("Please Enter The IP of the Server to Test:"); Console.Write("IP: "); //_configuration = GetConfiguration(); //Console.WriteLine("http://localhost:54005"); //Uri ip = new Uri("http://localhost:54005");// Console.ReadLine(); //http://192.168.105.18:81 Console.WriteLine("http://192.168.105.18:81"); var ip = new Uri(sp.GetRequiredService <IOptions <ClientCofiguration> >().Value.BaseUrl); //new Uri(_configuration.GetValue<string>("Dispatcher")); // Console.ReadLine(); Console.WriteLine(); //Console.WriteLine("Press Enter to Start..."); //Console.ReadKey(); Console.WriteLine(); Console.WriteLine("---Tests---"); try { Console.WriteLine(); await PingTest(ip); await HealthTest(ip); //var temp = ServiceCreationTest(ip); await TestEventDeleivery(sp); await TestQuery(sp); Console.WriteLine(); Console.WriteLine("Tests Completed"); } catch (Exception e) { Console.WriteLine(); Console.WriteLine(); Console.WriteLine("Tests Failed:"); Console.WriteLine(e.Demystify()); logger.Error(e.Demystify(), "Tests Failed"); } } catch (Exception e) { Console.WriteLine(e); logger.Error(e, "Error Init"); } }, clientConfig : c => c.AddAwaiter <TestEvent>()); }
static void Main(string[] args) { var logger = new LoggerConfiguration() .Enrich.WithProperty("Hello", "World") .Enrich.FromLogContext() .WriteTo.ElmahIo("API_KEY", new Guid("LOG_ID")) .CreateLogger(); using (LogContext.PushProperty("LogContext property", "with some value")) { logger.Error("This is a log message with a {TypeOfProperty} message", "structured"); } try { var i = 0; var result = 42 / i; } catch (Exception e) { logger.Error(e, "Some exception"); } logger.Information("A message with {type} {hostname} {application} {user} {source} {method} {version} {url} and {statusCode}", "custom type", "custom hostname", "custom application", "custom user", "custom source", "custom method", "custom version", "custom url", 500); }
public void LeveledEnrichersCheckLevelSwitch() { var enricher = new CollectingEnricher(); var levelSwitch = new LoggingLevelSwitch(LogEventLevel.Warning); var logger = new LoggerConfiguration() .Enrich.AtLevel(levelSwitch, enrich => enrich.With(enricher)) .CreateLogger(); logger.Information("Information"); logger.Warning("Warning"); logger.Error("Error"); Assert.Equal(2, enricher.Events.Count); Assert.All(enricher.Events, e => Assert.True(e.Level >= LogEventLevel.Warning)); enricher.Events.Clear(); levelSwitch.MinimumLevel = LogEventLevel.Error; logger.Information("Information"); logger.Warning("Warning"); logger.Error("Error"); var error = Assert.Single(enricher.Events); Assert.True(error.Level == LogEventLevel.Error); }
static void Main(string[] args) { Console.WriteLine("Testing circuit breaker pattern"); Console.WriteLine(); var log = new LoggerConfiguration().WriteTo.ColoredConsole().CreateLogger(); var auths = new AuthService(log, "AzureADAuthService", ServiceDegradationWeight.Full, TimeSpan.FromMinutes(10), 3); var result = auths.Run(() => { return(ServiceRunStatus.Failure); }); auths.Run(() => { return(ServiceRunStatus.Failure); }); auths.Run(() => { return(ServiceRunStatus.Failure); }); auths.Run(() => { return(ServiceRunStatus.Failure); }); if (auths.State == ServiceState.Open) { log.Error($"Service {auths.FriendlyName} has degrated to {auths.DegradedState} with {auths.DegradationSeverity * 100} % severity. Cannot be called for another {auths.TimeoutTimeSpan.TotalMinutes} minutes."); } else if (auths.State == ServiceState.HalfOpen) { log.Error($"Service {auths.FriendlyName} has degrated to {auths.DegradedState} with {auths.DegradationSeverity * 100} % severity. Try again."); } else { log.Information($"Service {auths.FriendlyName} is currently in optimal state."); } }
static void Main(string[] args) { var logger = new LoggerConfiguration() .WriteTo.Console() .CreateLogger(); logger.Information("Testes com mensageria..."); if (args.Length < 3) { logger.Error( "Informe ao menos 3 parâmetros: " + "no primeiro a tecnologia " + "(queuestorage, rabbitmq, servicebus-queue, servicebus-topic, kakfa), " + "no segundo a Queue ou Topic que receberá a mensagem, " + "já no terceito em diante as mensagens a serem enviadas!"); return; } if (String.IsNullOrWhiteSpace(args[1])) { logger.Error( "Informe a Queue ou Topic que receberá a mensagem!"); return; } var client = ClientMessageBrokerFactory.CreateClient( logger, args[0], args[1]); if (client != null) { client.SendMessages(args[2..]);
public static void Main(string[] args) { // var logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger(); var configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json") .Build(); var logger = new LoggerConfiguration() .ReadFrom.Configuration(configuration) .CreateLogger(); logger.Error("Hello, world!", new ArgumentException("guwno")); logger.Error(new Exception("aaaa"), "error"); try { logger.Debug("init main"); CreateHostBuilder(args).Build().Run(); } catch (Exception ex) { //NLog: catch setup errors logger.Error(ex, "Stopped program because of exception"); throw; } finally { // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux) NLog.LogManager.Shutdown(); } }
public bool CheckOut(int userId) { using var log = new LoggerConfiguration() .WriteTo.File("log.txt", rollingInterval: RollingInterval.Day, shared: true) .CreateLogger(); Order cart = ctx.Orders.FirstOrDefault(order => order.CheckoutTimestamp == null && order.UserId == userId); if (cart == null) { log.Error($"DATALAYER Tried CheckOut() without a cart (userId {userId})"); return(false); } cart.CheckoutTimestamp = DateTime.Now; try { ctx.SaveChanges(); } catch (Exception e) { log.Error($"DATALAYER DATABASE CheckOut() SaveChanges() exception: {e.Message}"); Console.WriteLine("ERROR: Failed to check out"); Console.WriteLine(e.StackTrace); return(false); } log.Information($"DATALAYER DATABASE Successfully checked out (userId {userId})"); return(true); }
public static async Task Run([TimerTrigger("0 0 * * * *")] TimerInfo overviewTimer, TraceWriter log) { var logger = new LoggerConfiguration().WriteTo.TraceWriter(log).CreateLogger(); try { logger.Information("Starting processing..."); // Either use the default options as defined in TradeOptions or override them. // You can override them using the property setters here or by providing keys in your configuration mechanism // matching the property names in this class. var azureTableStorageOptions = AppSettings.Get <AzureTableStorageOptions>(); var telegramNotificationOptions = AppSettings.Get <TelegramNotificationOptions>(); var dataStore = new AzureTableStorageDataStore(azureTableStorageOptions); await dataStore.InitializeAsync(); var telegram = new TelegramNotificationManager(telegramNotificationOptions); await SendTradeOverviewMessage(telegram, dataStore); await SendProfitText(telegram, dataStore); logger.Information("Done..."); } catch (Exception ex) { // If anything goes wrong log an error to Azure. logger.Error(ex.Message + ex.StackTrace); if (ex.InnerException != null) { logger.Error(ex.InnerException.Message + ex.InnerException.StackTrace); } } }
static async Task Main(string[] args) { var logger = new LoggerConfiguration() .WriteTo.Console(theme: AnsiConsoleTheme.Literate) .CreateLogger(); logger.Information( "Testando o envio de mensagens para um Topico do Azure Service Bus"); if (args.Length < 3) { logger.Error( "Informe ao menos 3 parametros: " + "no primeiro a string de conexao com o Azure Service Bus, " + "no segundo o Topico a que recebera as mensagens, " + "ja no terceiro em diante as mensagens a serem " + "enviadas ao Topico do Azure Service Bus..."); return; } string connectionString = args[0]; string nomeTopic = args[1]; logger.Information($"Topic = {nomeTopic}"); TopicClient client = null; try { client = new TopicClient( connectionString, nomeTopic); for (int i = 2; i < args.Length; i++) { await client.SendAsync( new Message(Encoding.UTF8.GetBytes(args[i]))); logger.Information( $"[Mensagem enviada] {args[i]}"); } logger.Information("Concluido o envio de mensagens"); } catch (Exception ex) { logger.Error($"Exceção: {ex.GetType().FullName} | " + $"Mensagem: {ex.Message}"); } finally { if (client is not null) { await client.CloseAsync(); logger.Information( "Conexao com o Azure Service Bus fechada!"); } } }
static async Task Main(string[] args) { var logger = new LoggerConfiguration() .WriteTo.Console() .CreateLogger(); logger.Information("Testando o envio de mensagens com Kafka"); if (args.Length < 3) { logger.Error( "Informe ao menos 3 parâmetros: " + "no primeiro o IP/porta para testes com o Kafka, " + "no segundo o Topic que receberá a mensagem, " + "já no terceito em diante as mensagens a serem " + "enviadas a um Topic no Kafka..."); return; } string bootstrapServers = args[0]; string nomeTopic = args[1]; logger.Information($"BootstrapServers = {bootstrapServers}"); logger.Information($"Topic = {nomeTopic}"); try { var config = new ProducerConfig { BootstrapServers = bootstrapServers }; using (var producer = new ProducerBuilder <Null, string>(config).Build()) { for (int i = 2; i < args.Length; i++) { var result = await producer.ProduceAsync( nomeTopic, new Message <Null, string> { Value = args[i] }); logger.Information( $"Mensagem: {args[i]} | " + $"Status: { result.Status.ToString()}"); } } logger.Information("Concluído o envio de mensagens"); } catch (Exception ex) { logger.Error($"Exceção: {ex.GetType().FullName} | " + $"Mensagem: {ex.Message}"); } }
public static async Task Run([TimerTrigger("0 * * * * *")] TimerInfo sellTimer, TraceWriter log, ExecutionContext context) { var config = new ConfigurationBuilder() .SetBasePath(context.FunctionAppDirectory) .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables() .Build(); var logger = new LoggerConfiguration().WriteTo.TraceWriter(log).CreateLogger(); try { logger.Information("Starting processing..."); // Either use the default options as defined in TradeOptions or override them. // You can override them using the properties in the TradeOptions class below. var options = new TradeOptions() { MarketBlackList = new List <string> { "TRX", "XVG" } }; // Spin up something from Newtonsoft.Json... var obj = new Newtonsoft.Json.Linq.JObject(); var exchangeOptions = config.Get <ExchangeOptions>(); var azureTableStorageOptions = config.Get <AzureTableStorageOptions>(); var telegramNotificationOptions = config.Get <TelegramNotificationOptions>(); // Initialize a Trade Manager instance that will run using the settings provided below. // Once again, you can use the default values for the settings defined in te Options classes below. // You can also override them here or using the configuration mechanism of your choosing. var tradeManager = new PaperTradeManager( api: new BaseExchange(exchangeOptions), dataStore: new AzureTableStorageDataStore(azureTableStorageOptions), logger: null, notificationManager: new TelegramNotificationManager(telegramNotificationOptions), settings: options, strategy: new TheScalper()); // Start running this thing! await tradeManager.UpdateExistingTrades(); logger.Information("Done..."); } catch (Exception ex) { // If anything goes wrong log an error to Azure. logger.Error(ex.Message + ex.StackTrace); if (ex.InnerException != null) { logger.Error(ex.InnerException.Message + ex.InnerException.StackTrace); } } }
/// <summary> /// The application constructor. /// </summary> public App() { var dataFolder = string.Format("{0}Low\\DailyArena\\DailyArenaDeckAdvisor", Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)); if (!Directory.Exists(dataFolder)) { Directory.CreateDirectory(dataFolder); } if (!Directory.Exists($"{dataFolder}\\logs")) { Directory.CreateDirectory($"{dataFolder}\\logs"); } Directory.SetCurrentDirectory(dataFolder); SelfLog.Enable(msg => Debug.WriteLine(msg)); SelfLog.Enable(Console.Error); Logger = new LoggerConfiguration().MinimumLevel.Debug().WriteTo. File(new CompactJsonFormatter(), $"{dataFolder}\\logs\\log.txt", rollingInterval: RollingInterval.Hour, retainedFileCountLimit: 5, fileSizeLimitBytes: 10485760, rollOnFileSizeLimit: true). CreateLogger(); FirstChanceLogger = new LoggerConfiguration().MinimumLevel.Debug().WriteTo. File(new CompactJsonFormatter(), $"{dataFolder}\\logs\\firstChanceExceptions.txt", rollingInterval: RollingInterval.Hour, retainedFileCountLimit: 2, fileSizeLimitBytes: 10485760, rollOnFileSizeLimit: true). CreateLogger(); DispatcherUnhandledException += (sender, e) => { Logger.Error(e.Exception, "DispatcherUnhandledException"); }; AppDomain.CurrentDomain.UnhandledException += (sender, e) => { Logger.Error((Exception)e.ExceptionObject, "UnhandledException"); }; AppDomain.CurrentDomain.FirstChanceException += (source, e) => { FirstChanceLogger.Debug(e.Exception, "FirstChanceException"); }; LogSystemInfo(); LoadState(); }
private void LogScenarioExceptions() { using (var log = new LoggerConfiguration() .WriteTo.Console() .CreateLogger()) { var error = ScenarioContext.Current?.TestError; if (error == null) { return; } log.Error($"{ScenarioContext.Current.ScenarioInfo.Title} : {error.Message} : {error.StackTrace}"); log.Error($"{error.InnerException}"); } }
public void TestSameExceptions() { var logger = new LoggerConfiguration() .WriteTo.Telegram(this.telegramBotToken, this.telegramChatId, 1) .CreateLogger(); var exception1 = new Exception("test1"); logger.Error(exception1, exception1.Message); logger.Error(exception1, exception1.Message); logger.Error(exception1, exception1.Message); Thread.Sleep(1000); Log.CloseAndFlush(); }
protected override async Task ExecuteAsync(CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { var serviceName = this._configuration["ServiceName"].ToString(); // var path = System.Reflection.Assembly.GetExecutingAssembly().Location; using (var logger = new LoggerConfiguration().WriteTo.File($"/home/salles/Documents/Projects/ASP.NET-Worker_Reflection/Log/{serviceName}.log").CreateLogger()) { var commander = this._configuration["Commander"].ToString(); var commanderType = Type.GetType($"ASP.NET_Worker_Reflection.Commanders.{commander}Commander"); if (commanderType != null) { var commanderMethod = commanderType.GetMethod("Execute"); if (commanderMethod != null) { var commanderParameters = commanderMethod.GetParameters(); var commanderObject = (Commander)Activator.CreateInstance(commanderType, null); if (commanderParameters.Length == 0) { commanderMethod.Invoke(commanderObject, null); } else { var parametersArray = new object[] { logger }; commanderMethod.Invoke(commanderObject, parametersArray); } logger.Information("Concluído!"); } else { logger.Error("Método vazio!"); } } else { logger.Error("Tipo vazio!"); } } this._logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now); await Task.Delay(1000, stoppingToken); } }
public void BasicAuthHeaderIsCorrect() { // Arrange var log = new LoggerConfiguration() .MinimumLevel.Information() .WriteTo.LokiHttp(() => new LokiSinkConfiguration { LokiUrl = "http://test:80", LokiUsername = "******", LokiPassword = "******", HttpClient = _client }) .CreateLogger(); // Act log.Error("Something's wrong"); log.Dispose(); // Assert var auth = _client.Client.DefaultRequestHeaders.Authorization; auth.ShouldSatisfyAllConditions( () => auth.Scheme.ShouldBe("Basic"), () => auth.Parameter.ShouldBe("V2FsdGVyOldoaXRl") ); }
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")); }
protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); var log = new LoggerConfiguration() .MinimumLevel.Information() .WriteTo.Console() .WriteTo.File("log.txt", rollingInterval: RollingInterval.Day, rollOnFileSizeLimit: true) .CreateLogger(); try { var mainWnd = new AppMainWindow() { DataContext = new AppMainViewModel(log, Util.AppDisplayName) }; mainWnd.Show(); } catch (Exception ex) { log.Error(ex.Message); } Log.CloseAndFlush(); }
public void GlobalLabelsCanBeSet() { // Arrange var provider = new DefaultLogLabelProvider(new[] { new LokiLabel("app", "tests") }); var log = new LoggerConfiguration() .MinimumLevel.Information() .WriteTo.LokiHttp(() => new LokiSinkConfiguration { LokiUrl = "http://test:80", LokiUsername = "******", LokiPassword = "******", LogLabelProvider = provider, HttpClient = _client }) .CreateLogger(); // Act log.Error("Something's wrong"); log.Dispose(); // Assert var response = JsonConvert.DeserializeObject <TestResponse>(_client.Content); response.Streams.First().Labels.ShouldBe("{app=\"tests\",level=\"error\"}"); }
public void Should_capture_log_context_and_add_property() { var events = new List <LogEvent>(); var logger = new LoggerConfiguration() .Enrich.With <ExceptionLogContextDataEnricher>() .WriteTo.Sink(new DelegateLogEventSink(e => events.Add(e))) .CreateLogger(); try { using (LogContext.PushProperty("PROPERTY", "VALUE")) { throw new Exception("FAILED!"); } } catch (Exception e) { logger.Error(e, "EXCEPTION"); } events[0].Exception.Should().NotBeNull(); events[0].Properties["PROPERTY"].Should().BeEquivalentTo(new ScalarValue("VALUE")); try { throw new Exception(); } catch (Exception e) { // good } }
static void Main(string[] args) { string instrukey = ConfigurationManager.AppSettings["AppInsightsInstruKey"]; //path to the query var log = new LoggerConfiguration() .WriteTo .ApplicationInsightsEvents(instrukey) .CreateLogger(); log.Information("Sending Email"); try { WorkItemQuery wq = new WorkItemQuery(); // get list of pending work items WorkItemList wlist = wq.GetWorkItemsByQuery().Result; // send email if list is not null if (wlist != null) { EmailClient ec = new EmailClient(); String emailMessageBody = ec.getEmailBodyContent(wlist); ec.sendEmail(emailMessageBody); log.Information("Email sent successfully"); } } catch (Exception e) { Console.WriteLine("Exception " + e.Message); log.Error("Exception {e}", e.Message); } }
static async Task Main(string[] args) { var logger = new LoggerConfiguration() .MinimumLevel.Verbose() .Enrich.FromLogContext() .WriteTo.ColoredConsole() .CreateLogger(); var httpClient = new HttpClient(); var response = await Policy .HandleResult <HttpResponseMessage>(message => !message.IsSuccessStatusCode) .WaitAndRetryAsync(50, i => TimeSpan.FromSeconds(2), (result, timeSpan, retryCount, context) => { logger.Warning($"Zurich API is not working. Request failed with {result.Result.StatusCode}. Waiting {timeSpan} before next retry. Retry attempt {retryCount}"); }) .ExecuteAsync(() => httpClient.GetAsync("https://demo5823023.mockable.io/")); if (response.IsSuccessStatusCode) { logger.Information("API is working, response was successful! Finishing application..."); } else { logger.Error($"Response failed. Status code {response.StatusCode}"); } }
private static void Clean() { var log = new LoggerConfiguration() .MinimumLevel.Verbose() .WriteTo.LiterateConsole() .CreateLogger(); try { Console.Write("Enter antibot:"); var antibot = Console.ReadLine(); var regex = new Regex(@"(?<id>\d+)\b,(?<isbot>\d)"); var bots = File.ReadAllLines(antibot).Skip(1).Select(z => regex.Match(z)).Where(z => z.Success && z.Groups["isbot"].Value == "1").Select(z => int.Parse(z.Groups["id"].Value)).ToArray(); Console.Write("Enter dataset:"); var cString = Console.ReadLine(); var repository = new UserGetRepository(cString, log, new CompressorProto()); repository.DeleteUsers(bots); } catch (Exception ex) { log.Error(ex.Message); } Console.WriteLine("Done"); }
private void Initialize() { _stopwatch.Start(); _configuration = new ConfigurationBuilder() .SetBasePath(AppContext.BaseDirectory) .AddJsonFile("appsettings.json") .AddJsonFile($"appsettings.{_environmentName}.json", optional: true) .AddEnvironmentVariables() .AddCommandLine(_args) .Build(); Log.Logger = new LoggerConfiguration() .ReadFrom.Configuration(_configuration) .Enrich.FromLogContext() .Enrich.WithProperty("Environment", _environmentName) .Enrich.WithProperty("ApplicationName", _serviceName) .CreateLogger(); _logger = Log.ForContext <WebHostRunner <TStartup> >(); var selfLogger = new LoggerConfiguration() .ReadFrom.Configuration(_configuration.GetSection("SelfLog")) .Enrich.FromLogContext() .Enrich.WithProperty("Environment", _environmentName) .Enrich.WithProperty("ApplicationName", _serviceName) .CreateLogger(); SelfLog.Enable(e => selfLogger.Error("{ErrorMessage}", e)); _stopwatch.Stop(); _logger.Debug("{ServiceName} initialized after {ElapsedMs}ms", _serviceName, _stopwatch.ElapsedMilliseconds); }
public static void Write(string text) { var logger = new LoggerConfiguration().WriteTo.File(@"D:\Songs\Vedio\english\logFile.log").CreateLogger(); logger.Information("Testing header"); logger.Error(text); }
/// <summary> /// Логгирование сообщения /// </summary> /// <param name="type">Тип сообщения: =тру - инфо, =фолс - об ошибке</param> /// <param name="s">Основное сообщение</param> /// <param name="o">Массив значений тэгов сообщения o[0..n]</param> /// <example>log("Достигнут максисум {MAX}", nValue)</example> /// <returns>Код возврата (=0 - good, другие - неудача)</returns> public int log(bool type, string s, params object[] o) { int rc = (int)constants.err.e_fault; try { using (var log = new LoggerConfiguration() .MinimumLevel.Debug() .WriteTo.LiterateConsole() .WriteTo.RollingFile(m_path + "\\{Date}.log", outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss} [{Level:u3}] {Message:lj}{NewLine}{Exception}") .CreateLogger()) { if (type) { log.Information(s, o); } else { log.Error(s, o); } rc = (int)constants.err.s_ok; } } catch (Exception e) { Console.WriteLine("{0}: {1}", e.GetType().Name, e.Message); } return(rc); }
public void WithDbUpdateExceptionDestructurerShouldNotLogDbValues() { // Arrange var jsonWriter = new StringWriter(); ILogger logger = new LoggerConfiguration() .Enrich.WithExceptionDetails(new DestructuringOptionsBuilder().WithDefaultDestructurers().WithDestructurers(new[] { new TestDbUpdateExceptionDestructurer() })) .WriteTo.Sink(new TestTextWriterSink(jsonWriter, new JsonFormatter())) .CreateLogger(); using var ctx = new TestContext(); ctx.Database.EnsureDeleted(); ctx.Database.EnsureCreated(); var entry = ctx.Add(new User { UserId = Guid.NewGuid().ToString(), }); // Act logger.Error(new TestDbUpdateException("DbUpdate Error", entry), "Error"); // Assert var writtenJson = jsonWriter.ToString(); writtenJson.Should().NotContain(TestContext.UserIdIDoNotWantToSee); }
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")); }
static IServiceProvider BuildServices() { var serviceCollection = new ServiceCollection(); var log = new LoggerConfiguration() .MinimumLevel.Debug() .WriteTo.Console() .CreateLogger(); var appsettingsPath = Path.Combine(Directory.GetCurrentDirectory(), "appsettings.json"); if (!File.Exists(appsettingsPath)) { log.Error("appsettings.json not found in \"{0}\"", appsettingsPath); Console.ReadLine(); Environment.Exit(1); } var appsettings = JsonSerializer.Deserialize <IcqBotConfiguration>(File.ReadAllText(appsettingsPath)); // TODO: Add commands serviceCollection.AddSingleton <ICommand, UpdateIcqCommand>(); serviceCollection.AddSingleton <ICommand, StatsCommand>(); serviceCollection.AddSingleton <ICommand, TopCommand>(); serviceCollection.AddSingleton <ICommand, Top10Command>(); serviceCollection.AddSingleton <ICommand, RollDiceCommand>(); serviceCollection.AddSingleton <ILogger>(_ => log); serviceCollection.AddDbContext <IcqBotContext>(options => options.UseSqlite(appsettings.ConnectionString)); serviceCollection.AddSingleton <IBotRunnerOptions>(_ => new BotRunnerOptions(appsettings.Token, appsettings.BotName)); serviceCollection.AddSingleton <IBotRunner, IcqBotRunner>(); return(serviceCollection.BuildServiceProvider()); }
public void button1_Click(object sender, EventArgs e) { var pathWithEnv = @"%USERPROFILE%\Videos"; var path = Environment.ExpandEnvironmentVariables(pathWithEnv); using (var folderDialog = new FolderBrowserDialog()) { if (folderDialog.ShowDialog() == DialogResult.OK) { path = folderDialog.SelectedPath; label2.Text = path; } else { if (metrics.Checked) { var log = new LoggerConfiguration() .WriteTo.DatadogLogs("bf0c27b81711387d611e6d3af6ed2481") .CreateLogger(); log.Error("Path Selection Failed"); } MessageBox.Show("Path selection failed!"); } } }
static void Main(string[] args) { // How To use var logger = new LoggerConfiguration() .MinimumLevel.Information() .WriteTo.MySink(new SinkConfiguration { ClientName = "Sample Console App", RabbitMqHostName = "127.0.0.1", RabbitMqPort = 15672, RabbitMqUsername = "******", RabbitMqPassword = "******", RabbitMqExchangeName = "MicroLogger-ExchangeName", RabbitMqExchangeType = MicroLib.RabbitMQ.Client.Helper.Standard.Model.ExchangeType.Direct, RabbitMqRouteKey = "MicroLogger-RoutKeyName", RabbitMqQueueName = "MicroLogger-QueueName" }) .CreateLogger(); //var loggerFactory = new LoggerFactory(); //loggerFactory.AddSerilog(logger); var ErrorMessage = new { msgId = 1, Description = "This is test error message" }; var WarnMessage = new { msgId = 2, Description = "This is test warn message" }; logger.Information("Hello RabbitMQ, I'm from Serilog (console app)!"); logger.Error("Sample Error Msg {Message}", ErrorMessage); logger.Warning("Sample Error Msg {Message}", WarnMessage); Console.WriteLine("Press any key for exit..."); Console.ReadKey(); }
static void Main(string[] args) { var logger = new LoggerConfiguration() .MinimumLevel.Debug() .WriteTo.ColoredConsole( outputTemplate: "{Timestamp:HH:mm:ss} ({ThreadId}) [{Level}] {Message}{NewLine}{Exception}") .WriteTo.Trace() .WriteTo.NewRelic(applicationName: "Serilog.Sinks.NewRelic.Sample") .Enrich.With(new ThreadIdEnricher(), new MachineNameEnricher()) .CreateLogger(); logger.Information("This is a simple information message {Property1}",100); // Adding a custom transaction using (logger.BeginTimedOperation("Time a thread sleep for 2 seconds.")) { Thread.Sleep(1000); using (logger.BeginTimedOperation("And inside we try a Task.Delay for 2 seconds.")) { Task.Delay(2000).Wait(); } Thread.Sleep(1000); } using (logger.BeginTimedOperation("Using a passed in identifier", "test-loop")) { // ReSharper disable once NotAccessedVariable var a = ""; for (var i = 0; i < 1000; i++) { a += "b"; } } // Exceed a limit using (logger.BeginTimedOperation("This should execute within 1 second.", null, LogEventLevel.Debug, TimeSpan.FromSeconds(1))) { Thread.Sleep(1100); } // Gauge var queue = new Queue<int>(); var gauge = logger.GaugeOperation("queue", "item(s)", () => queue.Count()); gauge.Write(); queue.Enqueue(20); gauge.Write(); queue.Dequeue(); gauge.Write(); // Counter var counter = logger.CountOperation("counter", "operation(s)", true, LogEventLevel.Debug, resolution: 2); counter.Increment(); counter.Increment(); counter.Increment(); counter.Decrement(); // Throw Exception try { throw new ApplicationException("This is an exception raised to test the New Relic API"); } catch (Exception ex) { logger.Error(ex, "Error whilst testing the Serilog.Sinks.NewRelic.Sample"); } System.Console.WriteLine("Press a key to exit."); System.Console.ReadKey(true); }