public void WrappingWarnsAboutNonDisposableWrapper()
        {
            var messages = new List <string>();

            SelfLog.Enable(s => messages.Add(s));

            new LoggerConfiguration()
            .WriteTo.Dummy(w => w.Sink <DisposeTrackingSink>())
            .CreateLogger();

            SelfLog.Disable();
            Assert.NotEmpty(messages);
        }
        public void Should_write_error_to_self_log()
        {
            var selfLogMessages = new StringBuilder();

            SelfLog.Enable(new StringWriter(selfLogMessages));

            // Exception occurs on creation - should be logged
            CreateLoggerThatCrashes();

            var selfLogContents = selfLogMessages.ToString();

            selfLogContents.Should().Contain("Failed to create the template");
        }
Exemple #3
0
 public Logger()
 {
     SelfLog.Enable(Console.Error);
     Serilog.Log.Logger = new LoggerConfiguration()
                          .MinimumLevel.Debug()
                          .WriteTo.Console()
                          .WriteTo.Elasticsearch(new ElasticsearchSinkOptions(new Uri("http://localhost:9200"))
     {
         AutoRegisterTemplate        = false,
         AutoRegisterTemplateVersion = AutoRegisterTemplateVersion.ESv6
     })
                          .CreateLogger();
 }
Exemple #4
0
        internal static void Register(ContainerBuilder builder)
        {
            builder.Register(c =>
            {
                var appMeta = c.Resolve <IAppMeta>();
                var loggingPathConfigurator = c.Resolve <LoggingPathConfigurator>();

                string logFilePath = Path.Combine(
                    loggingPathConfigurator.DefaultSavePath,
                    $"{appMeta.AppName}.log");

                // support self-logging
                SelfLog.Enable(s => Console.Error.WriteLine(s));

                LoggerConfiguration logConfiguration =
                    new LoggerConfiguration()
#if DEBUG
                    .MinimumLevel.Verbose()
#else
                    .MinimumLevel.Information()
#endif
                    .Enrich.With <EnvironmentEnricher>()
                    .Enrich.FromLogContext()
                    .Enrich.WithProperty("AppName", appMeta.AppName)
                    .Enrich.WithProperty("AppVersion", appMeta.AppVersion)
                    .Filter.ByExcluding(ExcludeTcpClientDisposeBugException)
                    .WriteTo.Console()
                    .WriteTo.File(logFilePath)
                    .ReadFrom.KeyValuePairs(ArgumentParser.GetArgsKeyValue(Environment.GetCommandLineArgs().ToArray()));

                foreach (var configureInstance in c.Resolve <IEnumerable <ILoggerSettings> >().ToList())
                {
                    logConfiguration.ReadFrom.Settings(configureInstance);
                }

                return(logConfiguration);
            })
            .AsSelf()
            .SingleInstance();

            builder.Register(
                c =>
            {
                Log.Logger = c.Resolve <LoggerConfiguration>().CreateLogger();
                return(Log.Logger);
            })
            .AutoActivate()
            .SingleInstance();

            builder.RegisterLogger();
        }
        static void Main(string[] args)
        {
            // Enable the selflog output
            SelfLog.Enable(Console.Error);
            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Debug()
                         .WriteTo.Console(theme: SystemConsoleTheme.Literate)
                                                                                                                                          //not persistant
                         .WriteTo.Elasticsearch(new ElasticsearchSinkOptions(new Uri(Configuration.GetConnectionString("elasticsearch"))) // for the docker-compose implementation
            {
                AutoRegisterTemplate = true,
                //BufferBaseFilename = "./buffer",
                RegisterTemplateFailure = RegisterTemplateRecovery.IndexAnyway,
                FailureCallback         = e => Console.WriteLine("Unable to submit event " + e.MessageTemplate),
                EmitEventFailure        = EmitEventFailureHandling.WriteToSelfLog |
                                          EmitEventFailureHandling.WriteToFailureSink |
                                          EmitEventFailureHandling.RaiseCallback,
                FailureSink = new FileSink("./fail-{Date}.txt", new JsonFormatter(), null, null)
            })
                         .CreateLogger();

            //SetupLoggerWithSimplePersistantStorage();
            //LoggingLevelSwitch levelSwitch = SetupLoggerWithPersistantStorage();

            //Log.Debug("To high loglevel default is Information this will not be logged");
            //levelSwitch.MinimumLevel = LogEventLevel.Debug;
            Log.Information("Hello, world!");
            //Log.Information("To  big log row bigger than SingleEventSizePostingLimit ! {a}", new string('*', 5000));

            int a = 10, b = 0;

            try
            {
                Log.Debug("Dividing {A} by {B}", a, b);
                Console.WriteLine(a / b);
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Something went wrong");
            }

            // Introduce a failure by storing a field as a different type
            Log.Debug("Reusing {A} by {B}", "string", true);

            Log.CloseAndFlush();
            Console.WriteLine("Press any key to continue...");
            while (!Console.KeyAvailable)
            {
                Thread.Sleep(500);
            }
        }
        static Flogger()
        {
            var connStr =
                ConfigurationManager.ConnectionStrings["FloggerConnection"].ToString();

            _perfLogger =
                new LoggerConfiguration()
                .WriteTo
                .MSSqlServer(
                    connStr,
                    "PerfLogs",
                    batchPostingLimit: 1,
                    autoCreateSqlTable: true,
                    columnOptions: GetSqlColumnOptions()
                    )
                .CreateLogger();
            _usageLogger =
                new LoggerConfiguration()
                .WriteTo
                .MSSqlServer(
                    connStr,
                    "UsageLogs",
                    batchPostingLimit: 1,
                    autoCreateSqlTable: true,
                    columnOptions: GetSqlColumnOptions()
                    )
                .CreateLogger();
            _errorLogger =
                new LoggerConfiguration()
                .WriteTo
                .MSSqlServer(
                    connStr,
                    "ErrorLogs",
                    batchPostingLimit: 1,
                    autoCreateSqlTable: true,
                    columnOptions: GetSqlColumnOptions()
                    )
                .CreateLogger();
            _diagnosticLogger =
                new LoggerConfiguration()
                .WriteTo
                .MSSqlServer(
                    connStr,
                    "DiagnosticLogs",
                    batchPostingLimit: 1,
                    autoCreateSqlTable: true,
                    columnOptions: GetSqlColumnOptions()
                    )
                .CreateLogger();
            SelfLog.Enable(msg => Debug.WriteLine(msg));
        }
Exemple #7
0
        static void Main(string[] args)
        {
            SelfLog.Enable(System.Console.WriteLine);

            Log.Logger = new LoggerConfiguration()
                         .Enrich.WithCaller()
                         .ReadFrom.Configuration(Configuration)
                         .CreateLogger();

            Log.Information("Hi there...");
            Log.Error("Error message sample {@Position}", new { Lat = 10, Long = 54 });

            Log.CloseAndFlush();
        }
Exemple #8
0
        private static void Main(string[] args)
        {
            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Debug()
                         .WriteTo.Console(theme: SystemConsoleTheme.Literate)
                         .WriteTo.Elasticsearch(
                new ElasticsearchSinkOptions(new Uri(
                                                 "https://search-fsd-customer-poc-nested-4rbwenablqhr7jzyjcr2gk64fq.eu-west-1.es.amazonaws.com")) // for the docker-compose implementation
            {
                AutoRegisterTemplate = true,
                //BufferBaseFilename = "./buffer",
                RegisterTemplateFailure = RegisterTemplateRecovery.IndexAnyway,
                FailureCallback         = e => Console.WriteLine("Unable to submit event " + e.MessageTemplate),
                EmitEventFailure        = EmitEventFailureHandling.WriteToSelfLog |
                                          EmitEventFailureHandling.WriteToFailureSink |
                                          EmitEventFailureHandling.RaiseCallback,
                FailureSink = new RollingFileSink("./fail-{Date}.txt", new JsonFormatter(), null, null)
            })
                         .CreateLogger();

            Stopwatch stopwatch = new Stopwatch();

            // Enable the selflog output
            SelfLog.Enable(Console.Error);

            stopwatch.Start();
            for (var i = 0; i < 2; i++)
            {
                Log.Information("Hello, world!");

                int a = 10, b = 0;
                try
                {
                    Log.Debug("Dividing {A} by {B}", a, b);
                    Console.WriteLine(a / b);
                }
                catch (Exception ex)
                {
                    Log.Error(ex, "Something went wrong");
                }

                // Introduce a failure by storing a field as a different type
                Log.Debug("Reusing {A} by {B}", "string", true);
            }
            stopwatch.Stop();
            Console.WriteLine("TIME ELAPSED: {0}", stopwatch.Elapsed);

            Log.CloseAndFlush();
            Console.Read();
        }
Exemple #9
0
        protected override void Load(ContainerBuilder builder)
        {
            builder.Register(context =>
            {
                var serviceName      = _config.GetValue <string>("logging:serviceName") ?? "MRReportingTool";
                var isConsoleEnabled = IsTrue(_config.GetValue <string>("logging:sinks:console:enabled"));
                var isSplunkEnabled  = IsTrue(_config.GetValue <string>("logging:sinks:splunk:enabled"));

                var defaultLogLevel = LogEventLevel.Debug;

                var loggerConfiguration = new LoggerConfiguration()
                                          .MinimumLevel.Verbose()
                                          .Enrich.WithProperty("Service", serviceName)
                                          .Enrich.WithThreadId()
                                          .Enrich.FromLogContext()
                                          .Enrich.WithCorrelationId();

                if (isConsoleEnabled)
                {
                    loggerConfiguration
                    .WriteTo
                    .Console(string.IsNullOrWhiteSpace(_config.GetValue <string>("logging:sinks:console:minimumLevel"))
                        ? defaultLogLevel : ParseLogLevel(_config.GetValue <string>("logging:sinks:console:minimumLevel")).Value);
                }

                if (isSplunkEnabled)
                {
                    var minimumLogLevel = string.IsNullOrWhiteSpace(_config.GetValue <string>("logging:sinks:splunk:minimumLevel"))
                    ? defaultLogLevel : ParseLogLevel(_config.GetValue <string>("logging:sinks:splunk:minimumLevel")).Value;

                    loggerConfiguration
                    .WriteTo
                    .EventCollector(_config.GetValue <string>("logging:sinks:splunk:host"),
                                    _config.GetValue <string>("logging:sinks:splunk:eventCollectorToken"),
                                    new SplunkJsonFormatter(minimumLogLevel <= defaultLogLevel),
                                    restrictedToMinimumLevel: minimumLogLevel);

                    SelfLog.Enable(Console.Error);
                    SelfLog.Enable(s =>
                    {
                        Console.WriteLine($"Serilog ERROR: {s}");
                    });
                }

                Log.Logger = loggerConfiguration.CreateLogger();
                return(Log.Logger);
            })
            .As <Serilog.ILogger>()
            .SingleInstance();
        }
Exemple #10
0
        public MainWindow()
        {
            InitializeComponent();

            SelfLog.Enable(message => Trace.WriteLine($"INTERNAL ERROR: {message}"));

            const string outputTemplate = "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj} {Properties:j}{NewLine}{Exception}";

            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Verbose()
                         .WriteTo.RichTextBox(_richTextBox, outputTemplate: outputTemplate, syncRoot: _syncRoot)
                         .Enrich.WithThreadId()
                         .CreateLogger();
        }
Exemple #11
0
    public static void Main(string[] args)
    {
        SelfLog.Enable(Console.Error);

        Log.Logger = new LoggerConfiguration()
                     .MinimumLevel.Debug()
                     .Enrich.WithThreadId()
                     .Enrich.WithProperty("meaning_of_life", 42)
                     .WriteTo.Console(outputTemplate: OutputTemplate)
                     .WriteTo.GrafanaLoki(
            "http://localhost:3100",
            new List <LokiLabel> {
            new() { Key = "app", Value = "console" }
        },
Exemple #12
0
        public void ShouldNotConvertInvalidHostname()
        {
            // Arrange
            string actualErrorMessage = null;

            SelfLog.Enable(output => { actualErrorMessage = output; });

            // Act
            var actual = "invalid-host-name".ToIPAddress();

            // Assert
            actual.ShouldBeNull();
            actualErrorMessage.ShouldNotBeNull();
        }
Exemple #13
0
        static void Main(string[] args)
        {
            // Enable the selflog output
            SelfLog.Enable(Console.Error);
            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Debug()
                         .WriteTo.Console(theme: SystemConsoleTheme.Literate)
                         .WriteTo.Elasticsearch(new ElasticsearchSinkOptions(new Uri(Configuration.GetConnectionString("elasticsearch"))) // for the docker-compose implementation
            {
                AutoRegisterTemplate        = true,
                OverwriteTemplate           = true,
                DetectElasticsearchVersion  = true,
                AutoRegisterTemplateVersion = AutoRegisterTemplateVersion.ESv7,
                NumberOfReplicas            = 1,
                NumberOfShards = 2,
                //BufferBaseFilename = "./buffer",
                RegisterTemplateFailure = RegisterTemplateRecovery.FailSink,
                FailureCallback         = e => Console.WriteLine("Unable to submit event " + e.MessageTemplate),
                EmitEventFailure        = EmitEventFailureHandling.WriteToSelfLog |
                                          EmitEventFailureHandling.WriteToFailureSink |
                                          EmitEventFailureHandling.RaiseCallback,
                FailureSink = new FileSink("./fail-{Date}.txt", new JsonFormatter(), null, null)
            })
                         .CreateLogger();

            Log.Information("Hello, world!");

            int a = 10, b = 0;

            try
            {
                Log.Debug("Dividing {A} by {B}", a, b);
                Console.WriteLine(a / b);
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Something went wrong");
            }

            // Introduce a failure by storing a field as a different type
            Log.Debug("Reusing {A} by {B}", "string", true);

            Log.CloseAndFlush();
            Console.WriteLine("Press any key to continue...");
            while (!Console.KeyAvailable)
            {
                Thread.Sleep(500);
            }
        }
        /// <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();
        }
        public TestLoggingModule(IServiceCollection services)
        {
            SelfLog.Enable(Console.WriteLine);

            Log.Logger = new LoggerConfiguration()
                         .WriteTo.Console()
                         .Enrich.FromLogContext()
                         .Enrich.WithMachineName()
                         .Enrich.WithThreadId()
                         .Enrich.WithEnvironmentUserName()
                         .Destructure.JsonNetTypes()
                         .CreateLogger();

            services.AddLogging(l => l.AddSerilog(Log.Logger));
        }
        public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
        .UseStartup <Startup>()
        .UseSerilog((hostingContext, loggerConfiguration) =>
        {
            loggerConfiguration
            .MinimumLevel.Verbose()
            .Enrich.FromLogContext()
            .Enrich.WithProperty("Environment", hostingContext.HostingEnvironment)
            .Enrich.WithProperty("HostName", Environment.MachineName)
            .WriteTo.Console(theme: SystemConsoleTheme.Literate);

            SelfLog.Enable(Console.Error);
        })
        .Build();
Exemple #17
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            SelfLog.Enable(Console.Error);

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.Run(async(context) =>
            {
                Log.Information("Api Application Test!");
                await context.Response.WriteAsync("Hello World!");
            });
        }
Exemple #18
0
        public static void Create()
        {
            Log.Logger = new LoggerConfiguration()
                         .ReadFrom.Configuration(Configuration)
                         .Enrich.FromLogContext()

                         // configure https://github.com/aws/aws-logging-dotnet
                         .WriteTo.AWSSeriLog(configuration: Configuration)

                         // configure https://github.com/Cimpress-MCP/serilog-sinks-awscloudwatch
                         .WriteTo.AmazonCloudWatch(new CloudWatchSinkOptions
            {
                // the name of the CloudWatch Log group for logging
                LogGroupName  = "Serilog.Cimpress",
                TextFormatter = new CompactJsonFormatter(),
                // other defaults defaults
                MinimumLogEventLevel = LogEventLevel.Information,
                BatchSizeLimit       = 30,
                QueueSizeLimit       = 10000,
                Period                = TimeSpan.FromSeconds(1),
                CreateLogGroup        = true,
                LogStreamNameProvider = new DefaultLogStreamProvider(),
                RetryAttempts         = 5
            }, new AmazonCloudWatchLogsClient())

                         // write to console too
                         .WriteTo.Console()

                         // in order to prove periodic PeriodicBatchingSink is not working as expected on AWS
                         .WriteTo.Sink(new CloudWatchLogSinkWithLogging(new AmazonCloudWatchLogsClient(), new CloudWatchSinkOptions
            {
                // the name of the CloudWatch Log group for logging
                LogGroupName  = "Serilog.Cimpress.Custom",
                TextFormatter = new CompactJsonFormatter(),
                // other defaults defaults
                MinimumLogEventLevel = LogEventLevel.Information,
                BatchSizeLimit       = 30,
                QueueSizeLimit       = 10000,
                Period                = TimeSpan.FromSeconds(1),
                CreateLogGroup        = true,
                LogStreamNameProvider = new DefaultLogStreamProvider(),
                RetryAttempts         = 5
            }))

                         .CreateLogger();

            SelfLog.Enable(Console.Error);
        }
Exemple #19
0
        public LoggerService(IOptions <SerilogEmailConfiguration> serilogEmailConfiguration)
        {
            _serilogEmailConfiguration = serilogEmailConfiguration;

            // Reading serilog configuration from appsettings.json
            var conf = new LoggerConfiguration()
                       .ReadFrom.Configuration(new ConfigurationBuilder()
                                               .SetBasePath(Directory.GetCurrentDirectory())
                                               .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                                               .Build(), "Serilog", null);

            // There is a problem on serilog.sinks.email package to read port number and other extra configs.
            // So we are additionally building serilog email configuration from appsettings.json
            if (_serilogEmailConfiguration.Value.Args != null)
            {
                var fromEmail          = _serilogEmailConfiguration.Value.Args.FromEmail;
                var toEmail            = _serilogEmailConfiguration.Value.Args.ToEmail;
                var mailServer         = _serilogEmailConfiguration.Value.Args.MailServer;
                var networkCredentials = new NetworkCredential
                {
                    UserName = _serilogEmailConfiguration.Value.Args.NetworkCredentials.Username,
                    Password = _serilogEmailConfiguration.Value.Args.NetworkCredentials.Password
                };
                var port = _serilogEmailConfiguration.Value.Args.Port;
                var batchPostingLimit = _serilogEmailConfiguration.Value.Args.BatchPostingLimit;
                var enableSsl         = _serilogEmailConfiguration.Value.Args.EnableSsl;
                var isBodyHtml        = _serilogEmailConfiguration.Value.Args.IsBodyHtml;
                var subject           = _serilogEmailConfiguration.Value.Args.MailSubject;
                var outputTemplate    = _serilogEmailConfiguration.Value.Args.OutputTemplate;

                conf.Enrich.FromLogContext()
                .Enrich.WithExceptionDetails()
                .WriteTo.Email(new EmailConnectionInfo
                {
                    EmailSubject       = subject,
                    EnableSsl          = enableSsl,
                    FromEmail          = fromEmail,
                    IsBodyHtml         = isBodyHtml,
                    MailServer         = mailServer,
                    NetworkCredentials = networkCredentials,
                    Port    = port,
                    ToEmail = toEmail
                }, outputTemplate, LogEventLevel.Error, batchPostingLimit, null);
            }

            _logger = conf.CreateLogger();
            SelfLog.Enable(msg => LogError(msg));
        }
        private static void Main(string[] args)
        {
            Log.Logger = new LoggerConfiguration()
                         .WriteTo.File("log-with-header.txt", outputTemplate: OUTPUT_TEMPLATE, hooks: new HeaderWriter(HEADER))
                         .CreateLogger();

            SelfLog.Enable(Console.Error);

            for (var i = 0; i < 10; i++)
            {
                Log.Information($"Log event {i}");
            }

            Console.WriteLine("Log events have been written to log-with-header.txt");
            Log.CloseAndFlush();
        }
        public static void Main()
        {
            SelfLog.Enable(Console.Out);

            var client = new AmazonKinesisClient();

            var streamOk = KinesisApi.CreateAndWaitForStreamToBecomeAvailable(
                kinesisClient: client,
                streamName: streamName,
                shardCount: shardCount
                );

            var loggerConfig = new LoggerConfiguration()
                               .WriteTo.ColoredConsole()
                               .MinimumLevel.Debug();

            if (streamOk)
            {
                loggerConfig.WriteTo.AmazonKinesis(
                    kinesisClient: client,
                    streamName: streamName,
                    period: TimeSpan.FromSeconds(2),
                    bufferBaseFilename: "./logs/kinesis-buffer",
                    onLogSendError: OnLogSendError
                    );
            }

            Log.Logger = loggerConfig.CreateLogger();

#if false
            for (var i = 0; i < 50; i++)
            {
                for (int j = 0; j < 500; j++)
                {
                    Thread.Sleep(1);
                    Log.Debug("Count: {i} {j}", i, j);
                }

                Console.Write(".");
            }
#endif

            LogStuff();

            Log.Fatal("That's all folks - and all done using {WorkingSet} bytes of RAM", Environment.WorkingSet);
            Console.ReadKey();
        }
Exemple #22
0
 public static IHostBuilder CreateHostBuilder(string[] args) =>
 Host.CreateDefaultBuilder(args)
 .UseSerilog((hostingContext, loggerConfiguration) =>
 {
     SelfLog.Enable(Console.WriteLine);
     // No DI here, so get option from Environment temporary.
     // see: https://github.com/serilog/serilog-aspnetcore/issues/169
     loggerConfiguration
     .ReadFrom.Configuration(hostingContext.Configuration)
     .Enrich.FromLogContext()
     //.Enrich.WithCorrelationIdHeader("TraceId")
     ;
 })
 .ConfigureWebHostDefaults(webBuilder =>
 {
     webBuilder.UseStartup <Startup>();
 });
Exemple #23
0
        public static void Main(string[] args)
        {
            SelfLog.Enable(Console.Error);

            var configuration = new ConfigurationBuilder()
                                .SetBasePath(Directory.GetCurrentDirectory())
                                .AddJsonFile("appsettings.json", true, true)
                                .AddUserSecrets(typeof(Program).Assembly)
                                .AddEnvironmentVariables()
                                .Build();

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

            CreateHostBuilder(args).Build().Run();
        }
Exemple #24
0
        public MainForm()
        {
            InitializeComponent();

            var richTextBoxHost = new ElementHost
            {
                Dock = DockStyle.Fill,
            };

            _richTextBoxPanel.Controls.Add(richTextBoxHost);

            var wpfRichTextBox = new System.Windows.Controls.RichTextBox
            {
                Background = Brushes.Black,
                Foreground = Brushes.LightGray,
                FontFamily = new FontFamily("Cascadia Mono, Consolas, Courier New, monospace"),
                FontSize   = 14,
                IsReadOnly = true,
                VerticalScrollBarVisibility   = ScrollBarVisibility.Auto,
                HorizontalScrollBarVisibility = ScrollBarVisibility.Auto,
                Margin = new Thickness(0),
            };

            richTextBoxHost.Child = wpfRichTextBox;
            _wpfRichTextBox       = wpfRichTextBox;

            _clearToolStripButton.Click          += Clear_OnClick;
            _logVerboseToolStripButton.Click     += LogVerbose_OnClick;
            _logDebugToolStripButton.Click       += LogDebug_OnClick;
            _logInformationToolStripButton.Click += LogInformation_OnClick;
            _logWarningToolStripButton.Click     += LogWarning_OnClick;
            _logErrorToolStripButton.Click       += LogError_OnClick;
            _logFatalToolStripButton.Click       += LogFatal_OnClick;
            _logParallelForToolStripButton.Click += LogParallelFor_OnClick;
            _logTaskRunToolStripButton.Click     += LogTaskRun_OnClick;

            SelfLog.Enable(message => Trace.WriteLine($"INTERNAL ERROR: {message}"));

            const string outputTemplate = "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj} {Properties:j}{NewLine}{Exception}";

            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Verbose()
                         .WriteTo.RichTextBox(wpfRichTextBox, outputTemplate: outputTemplate, syncRoot: _syncRoot)
                         .Enrich.WithThreadId()
                         .CreateLogger();
        }
Exemple #25
0
        public void WhenWaitingShouldCancel_OnDispose()
        {
            var wasCalled        = false;
            var writtenToSelfLog = false;

            SelfLog.Enable(_ => writtenToSelfLog = true);

            using (var timer = new PortableTimer(async delegate { await Task.Delay(50); wasCalled = true; }))
            {
                timer.Start(TimeSpan.FromMilliseconds(20));
            }

            Thread.Sleep(100);

            Assert.False(wasCalled, "tick handler was called");
            Assert.False(writtenToSelfLog, "message was written to SelfLog");
        }
        static async Task Main(string[] args)
        {
            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Information()
                         .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
                         .Enrich.FromLogContext()
                         .WriteTo.InfluxDB("Test App"                // Application Name
                                           , "Test Instance"         // Instance or Environment Name
                                           , "http://localhost:8086" // InfluxDb Address
                                           , "_internal")            // InfluxDb Database Name)
                         .CreateLogger();

            await BuildCommandLine()
            .UseHost(_ => Host.CreateDefaultBuilder(),
                     host =>
            {
                SelfLog.Enable(System.Console.Out);
                host.UseSerilog((hostingContext, loggerConfiguration) =>
                {
                    // could be configured here, but prefer earlier configuration
                })
                .ConfigureAppConfiguration((hostingContext, config) =>
                {
                    // The next 2 lines commented out as they are added by default in the correct order
                    // for more control first call config.Sources.Clear();
                    //config.AddJsonFile("appsettings.json", optional: true);
                    //config.AddEnvironmentVariables();
                    config.AddUserSecrets <Program>();
                    var configuration = config.Build();

                    if (args is null)
                    {
                        //add some defaults from config
                        var number = configuration.GetSection("Sample").GetValue <int>("number");
                        args       = new string[0];
                        args       = args.Append($"-n {number}").ToArray();
                    }

                    config.AddCommandLine(args);
                })
                .ConfigureServices((hostContext, services) =>
                {
                    services.AddOptions <SampleOptions>()
                    .Bind(hostContext.Configuration.GetSection(SampleOptions.Sample));
                });
            })
Exemple #27
0
        public ContainerBuilder WithFakeCommonProperties(int managedThreadId = 0, string machineName = null,
                                                         int processId       = 0, string processName = null, string threadName = null, string appDomainName = null)
        {
            _selfLogOutput = new StringWriter();
            SelfLog.Enable(TextWriter.Synchronized(_selfLogOutput));

            var mock = new Mock <ICommonProperties>();

            mock.SetupGet(m => m.ManagedThreadId).Returns(managedThreadId);
            mock.SetupGet(m => m.MachineName).Returns(machineName);
            mock.SetupGet(m => m.ProcessId).Returns(processId);
            mock.SetupGet(m => m.ProcessName).Returns(processName);
            mock.SetupGet(m => m.ThreadName).Returns(threadName);
            mock.SetupGet(m => m.AppDomainName).Returns(appDomainName);
            Container.RegisterInstance(mock.Object);
            return(this);
        }
        private static void Main(string[] args)
        {
            Log.Logger = new LoggerConfiguration()
                         .WriteTo.Kafka(
                new JsonFormatter(), new KafkaOptions(new List <string> {
                "kafka:9092"
            }, "console-example"),
                new BatchOptions())
                         .Enrich.FromLogContext()
                         .CreateLogger();

            Log.Information("Hello World!");

            SelfLog.Enable(message => System.Console.WriteLine(message));

            Log.CloseAndFlush();
        }
        public void CarriesMessageTemplateProperties()
        {
            var selfLog = new StringWriter();

            SelfLog.Enable(selfLog);

            var(logger, sink) = SetUp(LogLevel.Trace);

            logger.LogInformation("Hello, {Recipient}", "World");

            Assert.True(sink.Writes[0].Properties.ContainsKey("Recipient"));
            Assert.Equal("\"World\"", sink.Writes[0].Properties["Recipient"].ToString());
            Assert.Equal("Hello, {Recipient}", sink.Writes[0].MessageTemplate.Text);

            SelfLog.Disable();
            Assert.Empty(selfLog.ToString());
        }
Exemple #30
0
        internal static ILogger BuildLogger()
        {
            var serilogConfiguration = new ConfigurationBuilder()
                                       .SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
                                       .AddJsonFile("appsettings.json", false, true)
                                       .Build();

            Log.Logger = new LoggerConfiguration()
                         .WriteTo.ColoredConsole()
                         .MinimumLevel.Verbose()
                         .MinimumLevel.Override("Microsoft", LogEventLevel.Verbose)
                         .ReadFrom.Configuration(serilogConfiguration)
                         .CreateLogger();

            SelfLog.Enable(Console.WriteLine);

            return(Log.Logger);
        }