/// <summary> /// Start here /// </summary> /// <param name="args"></param> static void Main(string[] args) { var log = new LoggerConfiguration() .WriteTo.ColoredConsole(outputTemplate: " {Timestamp:HH:mm} [{Level}] ({ThreadId}) {Message}{NewLine}{Exception}") .MinimumLevel.Verbose() .WriteTo.File("log/log.txt", rollingInterval: RollingInterval.Day) // .WriteTo.File("log/Xog.txt", retainedFileCountLimit: 4, rollingInterval: RollingInterval.Minute) .WriteTo.File("log/Yog.txt", fileSizeLimitBytes: 1024, retainedFileCountLimit: 5, rollOnFileSizeLimit: true) .WriteTo.SQLite("db/test.db", tableName: "dataLog") .CreateLogger(); var userId = "mgasrs"; log.Debug($"User id is: {userId}"); log.Fatal("this is fatal"); // Highest log.Error("this is error"); log.Warning("this is warning"); log.Information("this is info"); log.Debug("this is debug"); log.Verbose("this is verbose"); // Lowest Console.ReadKey(); }
private static void Main(string[] args) { using (var log = new LoggerConfiguration() .MinimumLevel.Debug() // 要使用LogContext.PushProperty, Enrich.FromLogcontext()為必要 .Enrich.FromLogContext() .Enrich.WithProperty("Application", "Demo") // Package: Serilog.Enrichers.Environment .Enrich.WithMachineName() // Package: Serilog.Sinks.Console .WriteTo.Console() // Package: Serilog.Sinks.File .WriteTo.File("./log/log.txt") .WriteTo.File(new JsonFormatter(), "./log/log.json") // Package: Serilog.Formatting.Compact .WriteTo.File(new CompactJsonFormatter(), "./log/log.clef") .CreateLogger()) { try { throw new Exception("exception test"); } catch (Exception ex) { log.Error(ex, "Error Happened: {message}", ex.Message); } log.Debug("Test"); log.Information("Hello, Serilog!"); log.Warning("Goodbye, Serilog."); // 加入特定property var specialLog = log.ForContext("Customer", "Mike"); specialLog.Warning("A very rich man! balance: {balance} millions", 100); // 以某個Class為Property (property name: SourceProperty) var contextLog = log.ForContext <SomeContext>(); contextLog.Warning("context log"); // 動態加入property using (LogContext.PushProperty("OrderNumber", "ABC123")) { using (LogContext.PushProperty("TransactionId", "T12345")) { log.Debug("this log has TransactionId"); using (LogContext.PushProperty("OrderNumber", "ABC123")) { log.Debug("this log has OrderNumber"); } } log.Debug("this log has no TransactionId"); } log.Debug("this log has no OrderNumber"); } }
static async Task Main(string[] args) { // load serilog.json to IConfiguration var configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) // reloadOnChange will allow you to auto reload the minimum level and level switches .AddJsonFile(path: "serilog.json", optional: false, reloadOnChange: true) .Build(); // build Serilog logger from IConfiguration var log = new LoggerConfiguration() .ReadFrom.Configuration(configuration) .CreateLogger(); while (true) { log.Verbose("This is a Verbose log message"); log.Debug("This is a Debug log message"); log.Information("This is an Information log message"); log.Warning("This is a Warning log message"); log.Error("This is a Error log message"); log.Fatal("This is a Fatal log message"); await Task.Delay(1000); } }
internal void Log(string message, LoggingLevels level) { using (var log = new LoggerConfiguration() .MinimumLevel.Information() .WriteTo.Console() .WriteTo.File("log.txt", rollingInterval: RollingInterval.Day, rollOnFileSizeLimit: true) .CreateLogger()) { switch (level) { case LoggingLevels.Debug: log.Debug(message); break; case LoggingLevels.Error: log.Error(message); break; case LoggingLevels.Information: log.Information(message); break; } } }
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")); }
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 void Main(string[] args) { Serilog.Debugging.SelfLog.Enable(msg => Console.WriteLine(msg)); Serilog.Sinks.Slack.SlackSink.ProxyUri = "url:8080"; Serilog.Sinks.Slack.SlackSink.ProxyAuthString = "Negotiate base64encoded user:pass"; var log = new LoggerConfiguration() .MinimumLevel.Verbose() //.WriteTo.Slack("C0W6DD7LZ", "xoxp-13773446566-13774642576-72300718082-1d35369b22", LevelAlias.Maximum) .WriteTo.Slack("Slack URL" //,(LogEvent l) => l.RenderMessage() ) .CreateLogger(); try { log.Verbose("This is an verbose message!"); log.Debug("This is an debug message!"); log.Information("This is an information message!"); log.Warning("This is an warning message!"); log.Error("This is an error message!"); throw new Exception("This is an exception!"); } catch (Exception exception) { log.Fatal(exception, "Exception catched at Main."); } Console.ReadLine(); }
private static async Task Main(string[] args) { await Parser.Default.ParseArguments <ToolOptions>(args) .WithParsedAsync(async toolOpts => { var collectionConfigs = CreateConfigurations(toolOpts).ToArray(); var logPath = Path.Join(toolOpts.LogsDirectory ?? "", $"transit_{DateTime.Now:yyyy_MM_dd}.log"); var log = new LoggerConfiguration() .MinimumLevel.Debug() .Enrich.WithProperty("Scope", "Runner") .WriteTo.Console(toolOpts.Verbose ? LogEventLevel.Debug : LogEventLevel.Information, "[{Timestamp:HH:mm:ss} {Level:u3}][{Scope}] {Message:lj}{NewLine}{Exception}") .WriteTo.File(logPath, outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}][{Scope}] {Message:lj}{NewLine}{Exception}") .CreateLogger(); var cts = new CancellationTokenSource(); Console.CancelKeyPress += (_, _) => { log.Debug("Cancellation was requested"); cts.Cancel(); }; await TransitRunner.RunAsync(log, collectionConfigs, IterateCycles(toolOpts.Runs), toolOpts.DryRun, TimeSpan.FromSeconds(toolOpts.NotificationInterval), cts.Token); }); }
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 static void Main(string[] args) { // Wait for RabbitMQ Thread.Sleep(10000); var config = new RabbitMQClientConfiguration { Port = 5672, DeliveryMode = RabbitMQ.RabbitMQDeliveryMode.Durable, Exchange = "serilog-sink-exchange", Username = "******", Password = "******", ExchangeType = "fanout" }; config.Hostnames.Add("rabbitmq"); var logger = new LoggerConfiguration() .WriteTo.RabbitMQ((clientConfiguration, sinkConfiguration) => { clientConfiguration.From(config); sinkConfiguration.TextFormatter = new JsonFormatter(); }) .MinimumLevel.Verbose() .CreateLogger(); logger.Verbose("Verbose log entry"); logger.Debug("Debug log entry"); logger.Information("Information log entry"); logger.Warning("Warning log entry"); logger.Error("Error log entry"); logger.Fatal("Fatal log entry"); }
static void Main(string[] args) { var loggingLevelSwitch = new LoggingLevelSwitch(LogEventLevel.Verbose); var logger = new LoggerConfiguration() .MinimumLevel.ControlledBy(loggingLevelSwitch) .WriteTo.Console(LogEventLevel.Verbose) .CreateLogger(); while (true) { logger.Verbose("Verbose"); logger.Debug("Debug"); logger.Information("Information"); logger.Warning("Warning"); logger.Error("Error"); logger.Fatal("Fatal"); Console.WriteLine($"Minimum level is {loggingLevelSwitch.MinimumLevel}"); Console.WriteLine("--------------------------------------------------"); Thread.Sleep(4000); } }
static void Main(string[] args) { // Check here to find out how to get this information from LogAnalytics here https://www.systemcenterautomation.com/2018/05/find-azure-log-analytics-keys/ const string WORKSPACE_ID = ""; const string AUTHENTICATION_ID = ""; var logger = new LoggerConfiguration() .WriteTo.AzureAnalytics(WORKSPACE_ID, AUTHENTICATION_ID, new ConfigurationSettings { LogName = nameof(CoreConsoleLogAnalytics) }) .CreateLogger(); logger.Fatal("{Number}: {Application} {severity} log", 1, nameof(CoreConsoleLogAnalytics), "Fatal"); logger.Error("{Number}: {Application} {severity} log", 1, nameof(CoreConsoleLogAnalytics), "Error"); logger.Warning("{Number}: {Application} {severity} log", 2, nameof(CoreConsoleLogAnalytics), "Warning"); logger.Information("{Number}: {Application} {severity} log", 2, nameof(CoreConsoleLogAnalytics), "Information"); logger.Debug("{Number}: {Application} {severity} log", 3, nameof(CoreConsoleLogAnalytics), "Debug"); logger.Verbose("{Number}: {Application} {severity} log", 3, nameof(CoreConsoleLogAnalytics), "Verbose"); logger.Dispose(); Console.WriteLine("Waiting 10secs for logs to be written"); Thread.Sleep(1000 * 10); }
static void Main(string[] args) { var logger = new LoggerConfiguration() .MinimumLevel.Verbose() .WriteTo.ColoredConsole() .WriteTo.RollingFile(@"E:\C#\Приват\RabbitMQ\Send\Logs\Log-{Date}.txt") .CreateLogger(); logger.Debug("The Send.cs was started"); var factory = new ConnectionFactory() { HostName = "localhost" }; logger.Debug("Created new Connectionfactory with name= {HostName}", factory.HostName); using (var connection = factory.CreateConnection()) { logger.Debug("Created new connection {connection}", connection.ToString()); using (var channel = connection.CreateModel()) { string queueName = "first"; channel.QueueDeclare( queue: queueName, durable: false, exclusive: false, autoDelete: false, arguments: null); logger.Debug("Created queye {name} ", queueName); string message = "Hello RabbitMQ!!"; var data = Encoding.UTF8.GetBytes(message); logger.Debug("Encoded message: {message} to bytes", message); channel.BasicPublish( exchange: "", routingKey: "first", basicProperties: null, body: data); logger.Information("Published data"); } Console.WriteLine("Press Enter to exit"); Console.ReadLine(); } }
static void Main(string[] args) { var random = new Random(); using (var log = new LoggerConfiguration() .MinimumLevel.Debug() //.WriteTo.LiterateConsole() .WriteTo.Console(new CompactJsonFormatter()) .CreateLogger()) { for (var i = 0; i < 10; i++) { var user = new { Name = $"Name {i}", Id = i }; log.Debug("User {user} was used", user); log.Debug("User {@user} was used", user); } } }
public void DebugLabelIsSet() { // Arrange var log = new LoggerConfiguration() .MinimumLevel.Debug() .WriteTo.LokiHttp(_credentials, httpClient: _client) .CreateLogger(); // Act log.Debug("Debug Level"); log.Debug("Debug Level 2"); log.Information("info Level"); log.Dispose(); // Assert var response = JsonConvert.DeserializeObject <TestResponse>(_client.Content); response.Streams.First().Labels.ShouldBe("{level=\"debug\"}"); }
private static void Main() { var logger = new LoggerConfiguration() .WriteTo.Udp("localhost", 9999, AddressFamily.InterNetwork, new Log4jTextFormatter()) .WriteTo.Console() .MinimumLevel.Verbose() .CreateLogger(); ////var logger = new LoggerConfiguration() //// .WriteTo.Udp("localhost", 9998, AddressFamily.InterNetwork, new Log4netTextFormatter()) //// .WriteTo.Console() //// .MinimumLevel.Verbose() //// .CreateLogger(); var sourceGenerator = new SourceGenerator(); var messageGenerator = new MessageGenerator(); var logLevelGenerator = new LogLevelGenerator(); while (true) { var source = sourceGenerator.Generate(); var message = messageGenerator.Generate(); switch (logLevelGenerator.Generate()) { case 1: logger.Information("Source: {@source}, Message: {@message}", source, message); break; case 2: logger.Warning("{@source}, {@message}", source, message); break; case 3: logger.Error("Something went wrong: {@source}, {@message}", source, message); break; case 4: var exception = new MissingFieldException(message.Value); logger.Fatal(exception, "Fatal Error!!! {@message}", message); break; case 5: case 6: logger.Debug("Simple debugging output {@source}, {@message}", source, message); break; default: logger.Verbose("{@source} = {@message}", source.Name, message.Value); break; } Thread.Sleep(1000); } }
/// <summary> /// Displays all of the application configurations based on the Configuration Provider. /// </summary> /// <param name="config"></param> public static void DebugConfigurationsWithSerilog( this IConfigurationRoot config) { var logger = new LoggerConfiguration() .ReadFrom.Configuration(config) .WriteTo.Console() .CreateLogger(); var allConfigurations = GetAllConfigurations(config); foreach (var provider in GetConfigurationsByProvider(config.Providers, allConfigurations)) { logger.Debug("Configuration Provider: {name} - Count: {count}", provider.Key, provider.Value.Count); foreach (var(path, value) in provider.Value) { logger.Debug("{provider} - {location} - {value}", provider.Key, path, value); } } }
/// <summary> /// Displays all of the application configurations based on the Configuration Provider. /// </summary> /// <param name="config"></param> public static void DebugConfigurationsWithSerilog(this IConfigurationRoot config) { var logger = new LoggerConfiguration() .ReadFrom.Configuration(config) .WriteTo.Console() .CreateLogger(); var allConfigurations = config.GetDebugView(); logger.Debug(allConfigurations); }
//public LogManager() //{ //} public void LogDebug(string message) { using (var log = new LoggerConfiguration().MinimumLevel.Debug().WriteTo.File("logs/log.txt", fileSizeLimitBytes: null, buffered: true, rollingInterval: RollingInterval.Day, restrictedToMinimumLevel: Serilog.Events.LogEventLevel.Information, outputTemplate: "{Timestamp:dd-MM-yyyy HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}", retainedFileCountLimit: null ).CreateLogger()) { log.Debug(message); Log.CloseAndFlush(); } }
public void Can_Initialize_With_Defaults() { var methodInfo = nameof(Can_Initialize_With_Defaults); using (var log = new LoggerConfiguration() .WriteTo.Loupe() .CreateLogger()) { log.Debug("This is a debug message about {methodInfo}", methodInfo); log.Error("This is an error message about {methodInfo}", methodInfo); } }
static void Main(string[] args) { Logger log = new LoggerConfiguration() .MinimumLevel.Verbose() .Enrich.FromLogContext() .Enrich.WithProperty("MyLabelPropertyName", "MyPropertyValue") .Enrich.WithThreadId() .WriteTo.Console() .WriteTo.LokiHttp(() => new LokiSinkConfiguration { LokiUrl = "http://*****:*****@Position} in {Elapsed:000} ms.", position, 34); using (LogContext.PushProperty("A", 1)) { log.Warning("Warning with Property A"); log.Fatal("Fatal with Property A"); } using (LogContext.PushProperty("MyAppendPropertyName", 1)) { log.Warning("Warning with Property MyAppendPropertyName"); log.Fatal("Fatal with Property MyAppendPropertyName"); } log.Dispose(); }
public void UnityConsoleSinkReceivesMessage() { bool logReceived = false; Application.logMessageReceived += (logString, stackTrace, type) => logReceived = true; var logger = new LoggerConfiguration() .WriteTo.UnityConsole() .MinimumLevel.Debug() .CreateLogger(); logger.Debug("Test"); Assert.That(logReceived, Is.True); }
public static Logger 管道概念() { var logger = new LoggerConfiguration() .MinimumLevel.Debug() //这个被无效了 .WriteTo.Console() .MinimumLevel.Error() //MinimumLevel只有最后一个设置有用 如果要配置不同的logger还是用子logger吧 .WriteTo.Console() .CreateLogger(); logger.Debug("Nothing"); return(logger); }
public static void HelloLog() { // Create Logger var logger = new LoggerConfiguration() .WriteTo.Console() .CreateLogger(); // Output logs logger.Debug("Serilog Debugging message"); logger.Information("Serilog Information message"); logger.Warning("Serilog Warning message"); logger.Error("Serilog Error message"); logger.Fatal("Serilog Fatal message"); }
static void Main(string[] args) { var levelSwitch = new LoggingLevelSwitch(); levelSwitch.MinimumLevel = LogEventLevel.Debug; Logger log = new LoggerConfiguration() .WriteTo.File($"log_{DateTime.Now.ToString("dd_MM__hh_mm_ss")}.txt") .MinimumLevel.ControlledBy(levelSwitch) .CreateLogger(); log.Debug("Come bag"); log.Information($"{DateTime.Now.ToString()}"); log.Error($"{new ArgumentException().ToString()}"); levelSwitch.MinimumLevel = LogEventLevel.Error; log.Debug("Come bag"); log.Information($"{DateTime.Now.ToString()}"); log.Error($"{new ArgumentException().ToString()}"); Console.WriteLine("Serilog test"); }
/// <summary> /// Serilog의 포멧팅 /// </summary> internal void EmittingAndCllecting() { var itemNumber = 10; var itemcount = 999; //debug 부터 로그 남기기 설정 var log = new LoggerConfiguration().MinimumLevel.Debug().WriteTo.Console().CreateLogger(); //가로 안에 이름을 연동해서 쓸 수 있고 대소문자가 달라도 알아서 찾는다 log.Debug("Processing item {ItemNumber} of {ItemCount}", itemNumber, itemcount); var user = new { Name = "Nick", Id = "nblumhardt" }; log.Information("Logged on user {@User}", user); }
public void Can_Specify_Minimum_Severity() { var methodInfo = nameof(Can_Specify_Minimum_Severity); using (var log = new LoggerConfiguration() .WriteTo.Loupe(restrictedToMinimumLevel: LogEventLevel.Information) .CreateLogger()) { log.Debug("This is a debug message about {methodInfo} and should NOT be displayed", methodInfo); log.Verbose("This is a verbose message about {methodInfo} and should NOT be displayed", methodInfo); log.Information("This is an informational message about {methodInfo} and SHOULD be displayed", methodInfo); log.Error("This is an error message about {methodInfo} and SHOULD be displayed", methodInfo); } }
static void Main(string[] args) { var logger = new LoggerConfiguration().MinimumLevel.Verbose().WriteTo.RollingFile(@"E:\C#\Приват\RabbitMQ\Send\Logs\Log-{Date}.txt").WriteTo.ColoredConsole().CreateLogger(); var factory = new ConnectionFactory() { HostName = "localhost" }; logger.Debug("Created new factory {factory}", factory.HostName); using (var connection = factory.CreateConnection()) { logger.Debug("Created connection {connection}", connection.ToString()); using (var channel = connection.CreateModel()) { string queyeName = "first"; channel.QueueDeclare(queyeName, false, false, false, null); logger.Debug("Created queye {queye}", queyeName); var consumer = new EventingBasicConsumer(channel); logger.Debug("Created new consumer {consumer}", consumer.ToString()); consumer.Received += (model, ea) => { var data = ea.Body; var message = Encoding.UTF8.GetString(data); logger.Debug("Get messagge from ea.Body {message}", message); System.Console.WriteLine(message); }; channel.BasicConsume("first", true, consumer); System.Console.WriteLine("Type [enter] to exit"); System.Console.ReadLine(); ; } } }
public void GivenRestrictedMinimumLevelMessagesAreWritten_FilteredLogEventsAreStoredInSink() { var logger = new LoggerConfiguration() .WriteTo.InMemory(restrictedToMinimumLevel: Events.LogEventLevel.Information) .CreateLogger(); logger.Verbose("Verbose Message"); logger.Debug("Debug Message"); logger.Information("Information Message"); InMemorySink.Instance .LogEvents .Should() .HaveCount(1); }
public static Logger 子日志() { var logger = new LoggerConfiguration() .MinimumLevel.Debug() .WriteTo.Console() .WriteTo.Logger(logger => logger .MinimumLevel.Information() .WriteTo.Console() ) .CreateLogger(); logger.Debug("Debug"); //在子日志中被过滤 logger.Information("Information"); //出现二次 return(logger); }
public void Can_Record_Exceptions_In_Message() { var methodInfo = nameof(Can_Record_Exceptions_In_Message); var unthrownException = new InvalidOperationException("The outermost exception", new ApplicationException("The innermost exception")); using (var log = new LoggerConfiguration() .WriteTo.Loupe() .CreateLogger()) { log.Debug(unthrownException, "This is a debug message with exception {unthrownException} about {methodInfo}", unthrownException, methodInfo); log.Error(unthrownException, "This is an error message with exception {unthrownException} about {methodInfo}", unthrownException, methodInfo); } }