CreateLogger() public method

Create a logger using the configured sinks, enrichers and minimum level.
To free resources held by sinks ahead of program shutdown, the returned logger may be cast to IDisposable and disposed.
public CreateLogger ( ) : System.Logger
return System.Logger
        public Function()
        {
            var configuration = new ConfigurationBuilder()
                                .AddEnvironmentVariables()
                                .Build();

            System.Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(configuration["Pipeline:ManualIntervention:Slack:WebhookUrl"]));

            webhookUrl = configuration["Pipeline:ManualIntervention:Slack:WebhookUrl"];

            var services = new ServiceCollection();

            services.AddLogging();
            var serviceProvider = services.BuildServiceProvider();

            var loggerFactory = serviceProvider.GetRequiredService <ILoggerFactory>();

            var loggerConfig = new Serilog.LoggerConfiguration()
#if DEBUG
                               .MinimumLevel.Debug()
#endif
                               .Enrich.FromLogContext()
                               .Enrich.WithProperty("Application", "CodePipeline.ManualIntervention.Slack")
                               .WriteTo.Console(new JsonFormatter());

            Serilog.Log.Logger = loggerConfig.CreateLogger();
            loggerFactory.AddSerilog();

            logger = serviceProvider.GetRequiredService <ILogger <Function> >();
        }
Example #2
0
        protected override void Load(ContainerBuilder builder)
        {
            //Register components here
            builder.RegisterType<Service>().As<IService>();
            builder.RegisterType<WindowsService>().As<ServiceControl>();
            builder.RegisterType<OwinStartup>().As<IOwinStartup>();
            builder.RegisterType<NancyBootstrapper>().As<INancyBootstrapper>();

            builder.RegisterType<Config>().As<IConfig>();

            var loggerConfiguration = new LoggerConfiguration()
                    .Enrich.WithThreadId()                      //Add threadId for each log entry
                    .Enrich.FromLogContext()                    //Allow to add context values
                    .Enrich.WithProperty("RuntimeVersion", Environment.Version)
                    .WriteTo.FileSinkDefinedFromConfig();

            Log.Logger = loggerConfiguration.CreateLogger();

            builder.RegisterInstance(Log.Logger).As<ILogger>();

            builder.RegisterType<RequeueAndRemove>().As<IRequeueAndRemove>();
            builder.RegisterType<BusMonitor>().As<IBusMonitor>().SingleInstance();
            builder.RegisterType<Sender>().As<ISender>().SingleInstance();

            builder.Register(c => NamespaceManager.CreateFromConnectionString(c.Resolve<IConfig>().BusConnectionString)).As<NamespaceManager>();
            builder.Register(c => MessagingFactory.CreateFromConnectionString(c.Resolve<IConfig>().BusConnectionString)).As<MessagingFactory>();

            builder.RegisterType<BusManagerModule>().AsSelf().AsImplementedInterfaces();

            builder.RegisterAllImplementationsInAssembly<IModelBuilderBase>(typeof(QueueMessagesBuilder).Assembly);
            builder.RegisterAllImplementationsInAssembly<ICommandHandlerBase>(typeof(RequeueMessageCommandHandler).Assembly);
        }
Example #3
0
    public static ILoggerFactory CreateLoggerFactory(LogLevel logLevel, string logFilePath,
                                                     LogLevelSignal?signalOrNull)
    {
        if (string.IsNullOrWhiteSpace(logFilePath))
        {
            throw new ArgumentException("Value cannot be null or whitespace.", nameof(logFilePath));
        }

        var logLevelSwitch = new LoggingLevelSwitch {
            MinimumLevel = ConvertLevel(logLevel)
        };

        if (signalOrNull != null)
        {
            signalOrNull.LogLevelChanged += (_, level) => logLevelSwitch.MinimumLevel = ConvertLevel(level);
        }

        var configuration = new Serilog.LoggerConfiguration()
                            .MinimumLevel.ControlledBy(logLevelSwitch)
                            .Enrich.FromLogContext()
                            .WriteTo
                            .File(
            logFilePath,
            outputTemplate:
            "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} {Level:u3}] [{SourceContext}]{Scope} {Message:lj}{NewLine}{Exception}",
            rollingInterval: RollingInterval.Day);

        var logger = configuration.CreateLogger();

        return(new LoggerFactory(new[] { new SerilogLoggerProvider(logger) }));
    }
Example #4
0
        protected void Application_Start()
        {
            RouteTable.Routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            RouteTable.Routes.LowercaseUrls = true;

            AreaRegistration.RegisterAllAreas();

            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

            var Logger = new LoggerConfiguration()
                .WriteTo.Seq(Properties.Settings.Default.SeqLogUrl, apiKey: Properties.Settings.Default.SeqLogKey, bufferBaseFilename: AppDomain.CurrentDomain.BaseDirectory + @"App_Data\Logs")
                .Enrich.WithMachineName()
                .Enrich.With<HttpRequestUrlEnricher>()
                .Enrich.WithThreadId()
                .Enrich.With<HttpRequestClientHostIPEnricher>()
                .Enrich.WithProcessId()
                .Enrich.With<HttpRequestIdEnricher>()
                .Enrich.With<HttpRequestTypeEnricher>()
                .Enrich.With<HttpRequestUserAgentEnricher>()
                .Enrich.With<HttpRequestUrlReferrerEnricher>();

            Log.Logger = Logger.CreateLogger();

            Log.Debug("Address API started.");
        }
Example #5
0
 public ILogger GetLogger()
 {
     var loggerConfig = new LoggerConfiguration()
         .WriteTo.ColoredConsole(LogEventLevel.Debug)
         .Enrich.With(new ProcessIdEnricher());
     return loggerConfig.CreateLogger();
 }
        public static ILogger Logging()
        {
            ApplicationLifecycleModule.IsEnabled = false;

            var assemblyName = Constants.WebAssembly.GetName().Name;
            var assemblyVersion = Constants.WebAssembly.GetName().Version;

            var minimumLogLevel = DefaultSettingsReader.Get<MinimumLogLevelSetting>();
            var environment = DefaultSettingsReader.Get<EnvironmentSetting>();
            var seqServerUri = DefaultSettingsReader.Get<SeqServerUriSetting>();

            var loggerConfig = new LoggerConfiguration()
                                .MinimumLevel.Is(minimumLogLevel)
                                .Enrich.FromLogContext()
                                .Enrich.WithMachineName()
                                .Enrich.WithThreadId()
                                .Enrich.With<HttpRequestIdEnricher>()
                                .Enrich.WithProperty("ApplicationName", assemblyName)
                                .Enrich.WithProperty("ApplicationVersion", assemblyVersion)
                                .Enrich.WithProperty("Environment", environment)
                                .WriteTo.Seq(seqServerUri.ToString())
                                .WriteTo.Trace();

            return loggerConfig.CreateLogger();
        }
        static ContainerBuilder RegisterApplication(IProgramOptions options)
        {
            var builder = new ContainerBuilder();
            builder.RegisterInstance(options).As<IProgramOptions>();

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

            builder.RegisterModule<LogicIocModule>();

            if (options.Interactive)
            {
                builder.RegisterModule(new ConsoleIocModule(logConfig));

                builder.RegisterType<ConsoleApplication>().As<IApplication>().SingleInstance();
            }
            else
            {
                builder.RegisterModule(new WebAppIocModule(logConfig));
                builder.RegisterType<WebApplication>().As<IApplication>().SingleInstance();
            }

            Log.Logger = logConfig.CreateLogger();
            builder.RegisterInstance(Log.Logger).As<ILogger>();

            return builder;
        }
Example #8
0
        public void Test4()
        {
            LoggerConfiguration config = new Serilog.LoggerConfiguration();

            List <string> _logContents = new List <string>();
            int           disposeCount = 0;
            Action        callback     = () =>
            {
                disposeCount++;
            };

            config.WriteTo.MapCondition <string>((logEvent) =>
            {
                return((logEvent.Properties.GetValueOrDefault("Name") as ScalarValue).Value.ToString());
            }, (key, logConfig) =>
            {
                logConfig.Sink(new TestSink(_logContents, callback));
            }, key => true, TimeSpan.FromSeconds(0));

            var logger = config.CreateLogger();

            var testLogger1 = logger.ForContext("Name", "Test1");

            testLogger1.Information("A");

            var testLogger2 = logger.ForContext("Name", "Test2");

            testLogger2.Information("A");

            testLogger1.Information("B");

            Assert.Equal(3, disposeCount);
        }
Example #9
0
 /// <summary>
 /// Initializes a new instance of the <see cref="TestWithSerilog"/> class.
 /// </summary>
 /// <param name="output">
 /// The Xunit output.
 /// </param>
 protected TestWithSerilog(ITestOutputHelper output)
 {
     var loggerConfig = new LoggerConfiguration()
         .MinimumLevel.Verbose()
         .WriteTo.TextWriter(new XunitOutputWriter(output));
     Logger = loggerConfig.CreateLogger();
 }
Example #10
0
        /// <summary>
        /// Create and return a serilog ILogger instance.  
        /// For convenience this also sets the global Serilog.Log instance
        /// </summary>
        /// <returns></returns>
        public static ILogger ConfigureLogging()
        {
            var loggerConfig = new LoggerConfiguration()
                //Enrich each log message with the machine name
                .Enrich.With<MachineNameEnricher>()
                //Accept verbose output  (there is effectively no filter)
                .MinimumLevel.Verbose()
                //Write out to the console using the "Literate" console sink (colours the text based on the logged type)
                .WriteTo.LiterateConsole()
                //Also write out to a file based on the date and restrict these writes to warnings or worse (warning, error, fatal)
                .WriteTo.RollingFile(@"Warnings_{Date}.txt", global::Serilog.Events.LogEventLevel.Warning);

            if (useSeq)
            {
                //Send events to a default installation of Seq on the local computer
                loggerConfig = loggerConfig.WriteTo.Seq("http://localhost:5341");
            }

            var logger = loggerConfig
                //Take all of that configuration and make a logger
                .CreateLogger();

            //Stash the logger in the global Log instance for convenience
            global::Serilog.Log.Logger = logger;

            return logger;
        }
        public static void Configure()
        {
            var logConfig = new LoggerConfiguration()
                .WriteTo.SignalR(GlobalHost.ConnectionManager.GetHubContext<LoggingHub>());

            Log.Logger = logConfig.CreateLogger();
        }
Example #12
0
        private Serilog.Core.Logger CreateLogger()
        {
            try
            {
                StringBuilder connectionString = new StringBuilder(Configuration.GetConnectionString("AirlineDB"));

                var options = new ColumnOptions();

                Serilog.LoggerConfiguration configuration = new Serilog.LoggerConfiguration()
                                                            .MinimumLevel.Debug()
                                                            .WriteTo.MSSqlServer(
                    connectionString: connectionString.ToString(),
                    tableName: "Logs",
                    schemaName: "dbo",
                    autoCreateSqlTable: true,
                    columnOptions: options
                    );

                return(configuration.CreateLogger());
            }
            catch (Exception)
            {
                throw;
            }
        }
Example #13
0
        static void Main(string[] args)
        {
            Console.WriteLine("I'm ALIVE!");

            var loggerConfiguration = new LoggerConfiguration()
                .WriteTo.ColoredConsole()
                .Enrich.WithMachineName()
                .MinimumLevel.Debug();
            var logger = loggerConfiguration.CreateLogger();
            Log.Logger = logger;

            Log.Information("Starting up. Testing out all things C# 6.");

            var sleepPeriodInSeconds = 60;
            if (args.Length > 0 && int.TryParse(args[0], out sleepPeriodInSeconds))
            {
                Log.Information("Sleep interval provided. Setting sleep period {SleepPeriodInSeconds}.", sleepPeriodInSeconds);
            }
            var sleepPeriod = TimeSpan.FromSeconds(sleepPeriodInSeconds);

            Log.Information("EC2 Host information, if any. {@Ec2MetaData}", Ec2MetaData.Create());

            while (true)
            {
                var coinToss = Random.Next(0, 2);
                Log.Information("Coin Toss... {CoinToss}", coinToss);

                var instance = coinToss == 0 ? new WithPropertyInit() : null;

                Log.Information("Doing Work... {NameOfProp}", instance?.NameOfProp());
                Log.Information("{@Instance}", instance);

                Thread.Sleep(sleepPeriod);
            }
        }
Example #14
0
        /// <summary>
        /// Service main entry point
        /// </summary>
        /// <param name="args">
        /// Startup parameters
        /// </param>
        public static void Main(string[] args)
        {
            // preset logger
            var loggerConfig = new LoggerConfiguration().MinimumLevel.Debug().WriteTo.ColoredConsole();
            var logger = loggerConfig.CreateLogger();
            Log.Logger = logger;

            var arguments = new Docopt().Apply(CommandUsage, args, exit: true);
            var configurations = new List<string>();

            ValueObject config;
            if (arguments.TryGetValue("--config", out config) && config != null)
            {
                configurations.Add(config.ToString());
            }

            Container = new WindsorContainer();

            AppDomain.CurrentDomain.UnhandledException += (sender, eventArgs) =>
                {
                    Log.Logger.Error(
                        eventArgs.ExceptionObject as Exception,
                        "{Type}: Unhandled domain exception from {SenderType}, terminating: {IsTerminating}\n{StackTrace}", 
                        "System",
                        sender?.GetType().Name ?? "unknown",
                        eventArgs.IsTerminating,
                        (eventArgs.ExceptionObject as Exception)?.StackTrace);
                };

            var system = Bootstrapper.ConfigureAndStart(Container, configurations.ToArray());
            Log.Logger.Warning("{Type}: Started", "System");
            Console.CancelKeyPress += (sender, eventArgs) =>
                {
                    Log.Logger.Warning("{Type}: Shutdown sequence initiated", "System");
                    var cluster = Akka.Cluster.Cluster.Get(system);

                    var timeout = TimeSpan.FromSeconds(10);
                    if (cluster.IsTerminated || cluster.State.Members.Count == 0)
                    {
                        system.Terminate().Wait(timeout);
                    }
                    else
                    {
                        cluster.LeaveAsync().Wait(timeout);
                        system.Terminate().Wait(timeout);
                    }

                    Log.Logger.Warning("{Type}: Hard stopped", "System");
                    eventArgs.Cancel = true;
                };

            system.StartNameSpaceActorsFromConfiguration();
            BaseInstaller.RunPostStart(Container);

            var waitedTask = new System.Threading.Tasks.TaskCompletionSource<bool>();
            system.WhenTerminated.ContinueWith(task => waitedTask.SetResult(true));
            waitedTask.Task.Wait();
            Log.Logger.Warning("{Type}: Stopped", "System");
        }
Example #15
0
        public static void InitializeLogger()
        {
            // Configure a startup Logger, prior to getting the Logger configuration from the ConfigurationRoot
            #region Startup logger
            // Serilog is the logging provider I picked to provide a logging solution for the VoiceAttack ATAP Plugin
            // Enable Serilog's internal debug logging. Note that internal logging will not write to any user-defined Sources
            //  https://github.com/serilog/serilog-sinks-file/blob/dev/example/Sample/Program.cs
            Serilog.Debugging.SelfLog.Enable(System.Console.Out);
            // Another example is at https://stackify.com/serilog-tutorial-net-logging/
            //  This brings in the System.Diagnostics.Debug namespace and writes the SelfLog there
            Serilog.Debugging.SelfLog.Enable(msg => Debug.WriteLine(msg));
            Serilog.Debugging.SelfLog.WriteLine("in InitializeLogger(Serilog Self Log)");
            // Another example is at https://github.com/serilog/serilog-extensions-logging/blob/dev/samples/Sample/Program.cs
            // Another is https://nblumhardt.com/2019/10/serilog-in-aspnetcore-3/
            // Creating a `LoggerProviderCollection` lets Serilog optionally write events through other dynamically-added MEL ILoggerProviders.
            // var providers = new LoggerProviderCollection();

            // Setup Serilog's static Logger with an initial configuration sufficient to log startup errors
            // create a local Serilog Logger for use during Program startup
            var serilogLoggerConfiguration = new Serilog.LoggerConfiguration()
                                             .MinimumLevel.Verbose()
                                             .Enrich.FromLogContext()
                                             //.Enrich.WithExceptionDetails()
                                             .Enrich.WithThreadId()
                                             // .WriteTo.Console(outputTemplate: "Static startup Serilog {Timestamp:HH:mm:ss zzz} [{Level}] ({Name:l}) {Message}{NewLine}{Exception}")
                                             .WriteTo.Seq(serverUrl: "http://*****:*****@"C:\\Dropbox\\whertzing\\GitHub\\ATAP.Utilities\\_devlogs\\ATAP.Utilities.VoiceAttack.{Timestamp:yyyy-MM-dd HH:mm:ss}.log",
                fileSizeLimitBytes: 1024,
                outputTemplate:
                "Static startup Serilog {Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] {Message}{NewLine}{Exception}",
                rollingInterval: RollingInterval.Day, rollOnFileSizeLimit: true, retainedFileCountLimit: 31)
                                             .WriteTo.Debug();
            //.Enrich.WithHttpRequestId()
            //.Enrich.WithUserName()
            //.WriteTo.Providers(providers)

            Serilog.Core.Logger serilogLogger = serilogLoggerConfiguration.CreateLogger();
            // Set the Static Logger called Log to use this LoggerConfiguration
            Serilog.Log.Logger = serilogLogger;
            Serilog.Log.Debug("{0} {1}: The Serilog startup logger is defined with a default startup configuration", "PluginVA", "InitializeLogger");
            // Temp for testing the build configurations and the Trace #define
#if TRACE
            Serilog.Log.Debug("TRACE is defined");
#else
            Serilog.Log.Debug("TRACE is NOT defined");
#endif
            // end temp

            // MEL Logging causes problem with Logging.Abstractions assembly versions, neither net.5 V5.0.0 nor Net Desktop 4.8 3.16 version
            // Set the MEL LoggerFactory to use this LoggerConfiguration
            // Microsoft.Extensions.Logging.ILoggerFactory mELoggerFactory = new Microsoft.Extensions.Logging.LoggerFactory().AddSerilog();
            // Microsoft.Extensions.Logging.ILogger mELlogger = mELoggerFactory.CreateLogger("Program");
            #endregion
        }
        public static ILogger CreateLogger()
        {
            var config = new LoggerConfiguration();
            config
                .MinimumLevel.ControlledBy(new LoggingLevelSwitch { MinimumLevel = LogEventLevel.Debug })
                .WriteTo.ColoredConsole()
                .WriteTo.Trace();

            return config.CreateLogger();
        }
        protected override void Load(ContainerBuilder builder)
        {
            var configuration = new LoggerConfiguration()
                .ReadFrom.AppSettings()
                .Enrich.With<ThreadIdEnricher>();

            Log.Logger = configuration.CreateLogger();

            // configure Log to return our Serilog logger abstraction
            Core.Logging.Log.Customize(type => new SerilogLogger(Log.ForContext(type)));
        }
        private static void ConfigureLogging()
        {
            var loggingConfig = new LoggerConfiguration().WriteTo.ColoredConsole();

            if (!string.IsNullOrEmpty(StaticConfiguration.LoggingEndpoint))
            {
                loggingConfig.WriteTo.Seq(StaticConfiguration.LoggingEndpoint);
            }

            Log.Logger = loggingConfig.CreateLogger();
        }
        public static void Main()
        {
            SelfLog.Out = 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,
                    shardCount: shardCount,
                    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();
        }
        public static ILogger CreateLog()
        {
            //log messages can get pretty big, so it's nice to have a lot of space to view them:
            Console.WindowWidth = (int)(Console.LargestWindowWidth * 0.75);
            Console.BufferWidth = 300; //for extra long messages
            Console.WindowHeight = (int)(Console.LargestWindowHeight * 0.75);
            Console.BufferHeight = 2000; //so everything is visible

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

            return config.CreateLogger();
        }
Example #21
0
        public static ILoggerFactory CreateLoggerFactory(LogLevel logLevel)
        {
            var configuration = new Serilog.LoggerConfiguration()
                                .MinimumLevel.Is(ConvertLevel(logLevel))
                                .Enrich.FromLogContext()
                                .WriteTo
                                .Console(
                outputTemplate:
                "[{Timestamp:u} {Level:u3}] [{SourceContext}]{Scope} {Message}{NewLine}{Exception}");

            var logger        = configuration.CreateLogger();
            var loggerFactory = new LoggerFactory(new[] { new SerilogLoggerProvider(logger, true) });

            return(loggerFactory);
        }
Example #22
0
        public void Test6()
        {
            LoggerConfiguration config = new Serilog.LoggerConfiguration();

            List <string> _logContents = new List <string>();
            int           disposeCount = 0;
            Action        callback     = () =>
            {
                disposeCount++;
            };

            config.WriteTo.MapCondition <LogPathAndTimeKey>((logEvent) =>
            {
                LogPathAndTimeKey key = new LogPathAndTimeKey()
                {
                    Path = (logEvent.Properties.GetValueOrDefault("Name") as ScalarValue).Value.ToString(),
                    Time = logEvent.Timestamp.Date
                };
                return(key);
            }, (key, logConfig) =>
            {
                logConfig.Sink(new TestSink(_logContents, callback));
            }, key =>
            {
                DateTimeOffset now = DateTimeOffset.Now.Date.AddDays(1);
                if (now > key.Time.Date)
                {
                    return(true);
                }
                return(false);
            }, TimeSpan.FromSeconds(0));

            var logger = config.CreateLogger();

            var testLogger1 = logger.ForContext("Name", "Test1");

            testLogger1.Information("A");

            var testLogger2 = logger.ForContext("Name", "Test2");

            testLogger2.Information("A");

            testLogger1.Information("B");

            testLogger2.Information("A");

            Assert.Equal(4, disposeCount);
        }
Example #23
0
        /// <summary>
        /// 로그파일 초기화
        /// </summary>
        /// <param name="loggerName"></param>
        /// <param name="logsDirectory"></param>
        private static void InitializeLogger(string loggerName, string logsDirectory)
        {
            var minimumLevel           = LogEventLevel.Debug;
            var outputTemplate         = "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}";
            var pathFormat             = Path.Combine(logsDirectory, loggerName + ".{Date}.log");
            var retainedFileCountLimit = 100;
            var config = new Serilog.LoggerConfiguration()
                         .Enrich.FromLogContext()
                         .MinimumLevel.Is(minimumLevel)
                         .WriteTo.Logger(logger => logger.WriteTo.RollingFile(
                                             pathFormat: pathFormat,
                                             outputTemplate: outputTemplate,
                                             retainedFileCountLimit: retainedFileCountLimit));

            Log.Logger = config.CreateLogger();
        }
Example #24
0
        private static void SetupLogger(LoggerConfiguration loggerConfiguration, IConfiguration hostingContextConfiguration, string environmentName,
                                        bool isHostingEnvironmentProductionOrStagingOrDevelopment, IServiceCollection serviceCollection)
        {
            var applicationName     = loggerConfiguration.SerilogApplicationName;
            var applicationSlotName = $"{applicationName}:{environmentName}";

            var serilogConfiguration = new SerilogConfig().ReadFrom.Configuration(hostingContextConfiguration)
                                       .Enrich.WithProperty(PropertyNames.Application, applicationSlotName);

            var template = GetLogTemplate();

            if (isHostingEnvironmentProductionOrStagingOrDevelopment)
            {
                var instrumentationKey = loggerConfiguration.ApplicationInsightsInstrumentationKey;
                var telemetryClient    = new TelemetryClient {
                    InstrumentationKey = instrumentationKey
                };
                serilogConfiguration.WriteTo.ApplicationInsights(telemetryClient, LogEventsToTelemetryConverter);

                serviceCollection.AddSingleton(telemetryClient);
            }
            else
            {
                serilogConfiguration.WriteTo.Debug(outputTemplate: template);
            }

            if (loggerConfiguration.SerilogEnableLocalFileSink)
            {
                serilogConfiguration.WriteTo.RollingFile("logs/log-{Date}.txt",
                                                         outputTemplate: template,
                                                         fileSizeLimitBytes: loggerConfiguration.SerilogFileSizeLimitMBytes * 1024 * 1024);
            }

            var logger = serilogConfiguration.CreateLogger();

            AppDomain.CurrentDomain.UnhandledException += (sender, args) =>
            {
                logger.Event("UnhandledExceptionCaughtByAppDomainUnhandledExceptionHandler")
                .With.Message("Exception object = '{@ExceptionObject}'; Is terminating = '{IsTerminating}'", args.ExceptionObject,
                              args.IsTerminating)
                .AsFatal();
            };

            Log.Logger = logger;
        }
Example #25
0
        private void Initialize()
        {
            _mainConfig = new LoggerConfiguration(); // set the main config for console and file logs.
            SetupConfiguration(_mainConfig); // setup the configuration with enrichers and so.

            // create the default console.
#if DEBUG
            _mainConfig.WriteTo.ColoredConsole(LogEventLevel.Debug, ConsoleLogFormat); // use debug level for debug mode.
#else
            _mainConfig.WriteTo.ColoredConsole(LogEventLevel.Information, ConsoleLogFormat); // use information level for release mode.
#endif
            // bind the config to global log.
            Log.Logger = _mainConfig.CreateLogger();

            // set the packet log configuration.
            _packetLoggerConfig = new LoggerConfiguration(); // will be used for packet logger.
            SetupConfiguration(_packetLoggerConfig); // setup the configuration with enrichers and so.
        }
        public static void Configure()
        {
            var logConfig = new LoggerConfiguration()
                .WriteTo.SignalR(GlobalHost.ConnectionManager.GetHubContext<LoggingHub>());

            try
            {
                var setting = CloudConfigurationManager.GetSetting("StorageConnectionString");
                var storage = CloudStorageAccount.Parse(setting);

                logConfig.WriteTo.AzureTableStorage(storage);
            }
            catch
            {
            }

            Log.Logger = logConfig.CreateLogger();
        }
Example #27
0
        static Log()
        {
            // configure Log4Net
            XmlConfigurator.Configure();
            //ILog log4netLog = LogManager.GetLogger("Application.Logger");

            // Get current folder to write log file to.
            string currentFolder = Assembly.GetExecutingAssembly().Location;
            string logFilePathName = Path.Combine(currentFolder, "log.txt");
            log4net.GlobalContext.Properties["LogFileName"] = logFilePathName;

            // configure Serilog Logger
            LoggerConfiguration config = new LoggerConfiguration();
            config.WriteTo.ColoredConsole();
            config.WriteTo.Log4Net(defaultLoggerName: "Application.Logger");
            // config.WriteTo.Seq("http://localhost:5341/");
            Logger = config.CreateLogger();
        }
        private static ILogger ConfigureLogging()
        {
            Serilog.Log.Logger = new DoNotUseTheStaticLogger();
            SelfLog.Out = Console.Out;

            var loggerConfiguration = new LoggerConfiguration()
                .ReadFrom.AppSettings()
                .Enrich.WithProperty("AppName", "Insight-BDD-Test")
                .WriteTo.Seq("http://localhost:5341")
                .Enrich.WithMachineName();

            if (Environment.UserInteractive)
            {
                loggerConfiguration.WriteTo.ColoredConsole();
            }

            return loggerConfiguration.CreateLogger()
                .ToNephilaILogger();
        }
Example #29
0
 public void Configure()
 {
     var logConfiguration = new LoggerConfiguration()
         .MinimumLevel.Is(_minimumLogLevel)
         .Enrich.FromLogContext()
         .Enrich.WithMachineName()
         .Enrich.WithThreadId()
         .Enrich.With<HttpRequestIdEnricher>()
         .Enrich.With<UserNameEnricher>()
         .Enrich.WithProperty("ApplicationName", _applicationName)
         .Enrich.WithProperty("ApplicationVersion", _thisAssembly.GetName().Version)
         .Enrich.WithProperty("EnvironmentName", _environmentName.Value)
         .Enrich.With<HttpRequestNumberEnricher>()
         .Enrich.With<HttpRequestRawUrlEnricher>()
         .Enrich.With<HttpRequestTraceIdEnricher>()
         .Enrich.With<HttpRequestTypeEnricher>()
         .Enrich.With<HttpRequestUserAgentEnricher>()
         .WriteTo.Seq(_seqServerUri);
     Log.Logger = logConfiguration.CreateLogger();
 }
        public void RoutesToCommonLogging()
        {

            // configure for capturing
            CapturingLoggerFactoryAdapter adapter = new CapturingLoggerFactoryAdapter();
            LogManager.Adapter = adapter;
            var configuration = new LoggerConfiguration().ReadFrom.AppSettings().Enrich.WithProperty("Common.Logging.Type", typeof(CommonLoggingSerilogTests).FullName);
            var logger = configuration.CreateLogger();

            var exception = new Exception();

            adapter.ClearLastEvent();

            var position = new { Latitude = 25, Longitude = 134 };
            var elapsedMs = 34;
            logger.Error(exception, "Processed {@Position} in {Elapsed:000} ms.", position, elapsedMs);

            Assert.AreEqual(typeof(CommonLoggingSerilogTests).FullName, adapter.LastEvent.Source.Name);
            Assert.AreEqual("Processed { Latitude: 25, Longitude: 134 } in 034 ms.", adapter.LastEvent.RenderedMessage);
            Assert.AreSame(exception, adapter.LastEvent.Exception);
        }
        /// <summary>
        /// This test is failing
        /// </summary>
        //[Fact]
        public void FailingTest()
        {
            var loggerConfig = new LoggerConfiguration().MinimumLevel.Verbose().WriteTo.TextWriter(new LocalXunitOutputWriter(this.output));
            Log.Logger = loggerConfig.CreateLogger();

            var config =
                ConfigurationFactory.ParseString(@"
                    akka : {
                        stdout-loglevel : INFO
                        loggers : [""Akka.Logger.Serilog.SerilogLogger, Akka.Logger.Serilog""]
                        log-config-on-start : on
                        loglevel : INFO

                        actor.deployment {
                            /SomeActor/workers {
                                    router = round-robin-pool
                                    nr-of-instances = 5
                                }
                        }
                    }").WithFallback(ConfigurationFactory.ParseString(@"
                        akka.actor.deployment {
                            /MyActor/workers {
                                    router = round-robin-pool
                                    nr-of-instances = 5
                                }
                        }
                    "));

            ActorSystem system = ActorSystem.Create("Test", config);
            try
            {
                var actor = system.ActorOf(Props.Create(() => new MyActor()), "MyActor");
                var result = actor.Ask<string>("hello world", TimeSpan.FromSeconds(1)).Result;
                Assert.Equal("hello world", result);
            }
            finally
            {
                system.Terminate().Wait(TimeSpan.FromSeconds(5));
            }
        }
Example #32
0
        public static void InitializeLogging(ILoggerConfiguration config)
        {
            string path1 = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "logs");

            Serilog.LoggerConfiguration loggerConfiguration = new Serilog.LoggerConfiguration().MinimumLevel.Debug().Enrich
                                                              .WithProperty("softwareName", (object)config.SoftwareName, false).Enrich.FromLogContext().WriteTo
                                                              .ColoredConsole(LogEventLevel.Verbose,
                                                                              "{Timestamp:yyyy-MM-dd HH:mm:ss} [{Level}] {Message}{NewLine}{Exception}", (IFormatProvider)null)
                                                              .WriteTo.RollingFile(Path.Combine(path1, config.SoftwareName + ".log"), LogEventLevel.Verbose,
                                                                                   "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] {Message}{NewLine}{Exception}",
                                                                                   (IFormatProvider)null, new long?(1073741824L), new int?(31));

            Log.Logger = loggerConfiguration.CreateLogger();

            Log.ForContext <ServiceBase>().Information("Configuration: {@config}", (object)config);

            AppDomain.CurrentDomain.UnhandledException += (UnhandledExceptionEventHandler)((sender, e) =>
            {
                Exception exceptionObject = e.ExceptionObject as Exception;
                Log.ForContext <ServiceBase>().Error(exceptionObject, exceptionObject.Message);
            });
        }
        public static void Bootstrap()
        {
            Configuration = new LoggerConfiguration()
                //log to console
                .WriteTo.Console(
                    outputTemplate:"{Timestamp:yyyy-MM-dd HH:mm:ss} {RequestId} [{Level}] {Message}{NewLine}{Exception}",
                    restrictedToMinimumLevel:LogEventLevel.Information)

                //elastic search
                .WriteTo.Elasticsearch(new ElasticsearchSinkOptions(new Uri("http://*****:*****@"C:\temp\elasticsearch",
                    MinimumLogEventLevel = LogEventLevel.Verbose,
                })

                //files is here
                .WriteTo.Sink(new FileSink("mag.logs", new JsonFormatter(), 2097152, Encoding.UTF8), LogEventLevel.Verbose);
            SelfLog.Out = Console.Out;

            Common.Logging.LogManager.Adapter = new SerilogFactoryAdapter(Configuration.CreateLogger());
        }
            public static ILogger CreateLogger(string logFilePattern, string seqUrl)
            {
                var config = new LoggerConfiguration()
                    .MinimumLevel.Verbose();

                config.WriteTo.ColoredConsole();

                if (!string.IsNullOrEmpty(logFilePattern))
                {
                    config = config.WriteTo.RollingFile(logFilePattern);
                }

                if (!string.IsNullOrEmpty(seqUrl))
                {
                    config = config.WriteTo.Seq(seqUrl);
                }

                InitialiseGlobalContext(config);

                Log.Logger = config.CreateLogger(); // register as global static
                return Log.Logger;
            }
Example #35
0
        public Function()
        {
            var configuration = new ConfigurationBuilder()
                                .AddEnvironmentVariables()
                                .Build();

            webhookUrl = configuration["Pipeline:EventHandler:Slack:WebhookUrl"];
            var tagList = configuration["Pipeline:EventHandler:Slack:TagList"];

            if (!string.IsNullOrEmpty(tagList))
            {
                tags = tagList.Split(",");
            }
            else
            {
                tags = new string[0];
            }

            var services = new ServiceCollection();

            services.AddLogging();
            var serviceProvider = services.BuildServiceProvider();

            var loggerFactory = serviceProvider.GetRequiredService <ILoggerFactory>();

            var loggerConfig = new Serilog.LoggerConfiguration()
#if DEBUG
                               .MinimumLevel.Debug()
#endif
                               .Enrich.FromLogContext()
                               .Enrich.WithProperty("Application", "CodePipeline.EventHandler.Slack")
                               .WriteTo.Console(new JsonFormatter());

            Serilog.Log.Logger = loggerConfig.CreateLogger();
            loggerFactory.AddSerilog();

            logger = serviceProvider.GetRequiredService <ILogger <Function> >();
        }
Example #36
0
        public ILogger Configurar(string variavelAmbiente)
        {
            var ambiente     = Environment.GetEnvironmentVariable(variavelAmbiente);
            var configuracao = new Serilog.LoggerConfiguration()
                               .MinimumLevel.Debug()
                               .MinimumLevel.Override(FonteLog.Microsoft, LogEventLevel.Information)
                               .MinimumLevel.Override(FonteLog.Sistema, LogEventLevel.Warning)
                               .Enrich.FromLogContext()
                               .Enrich.WithExceptionDetails()
                               .Enrich.WithMachineName();

            if (ambiente == EnvironmentName.Development)
            {
                configuracao.WriteTo.Console(theme: AnsiConsoleTheme.Code);
            }
            else
            {
                configuracao.WriteTo.Console(new ElasticsearchJsonFormatter());
            }

            Log.Logger = configuracao.CreateLogger();
            return(Log.Logger);
        }
Example #37
0
        private static void ConfigureSerilog(ILoggerFactory lf)
        {
            var curDir  = Directory.GetCurrentDirectory();
            var libPath = Assembly.GetEntryAssembly().Location;
            var libDir  = Path.GetDirectoryName(libPath);
            var libName = Path.GetFileNameWithoutExtension(libPath);
            //var logPath = Path.Combine(libDir, $"{libName}-serilog.log");
            var logPath = Path.Combine(curDir, $"{libName}-serilog.log");

            var outputTemplate = "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] ({SourceContext}) {Message:lj}{NewLine}{Exception}";
            var loggerConfig   = new Serilog.LoggerConfiguration()
                                 .Enrich.FromLogContext()
                                 // // .Destructure.ByTransforming<DynamicValue>(DestructureDynamicValue)
                                 .MinimumLevel.Verbose()
                                 .WriteTo.File(logPath
                                               //,restrictedToMinimumLevel: LogEventLevel.Verbose)
                                               , outputTemplate: outputTemplate);

            // AppSettings JSON can be configured as per:
            //  https://github.com/serilog/serilog-settings-configuration
            loggerConfig.ReadFrom.Configuration(ConfigUtil.Configuration);

            LoggerFactory.AddSerilog(loggerConfig.CreateLogger());
        }
 /// <summary>
 /// Create a <see cref="ReloadableLogger"/> for use during host bootstrapping. The
 /// <see cref="SerilogHostBuilderExtensions.UseSerilog(IHostBuilder, Action{HostBuilderContext, IServiceProvider, LoggerConfiguration}, bool, bool)"/>
 /// configuration overload will detect when <see cref="Log.Logger"/> is set to a <see cref="ReloadableLogger"/> instance, and
 /// reconfigure/freeze it so that <see cref="ILogger"/>s created during host bootstrapping continue to work once
 /// logger configuration (with access to host services) is completed.
 /// </summary>
 /// <param name="loggerConfiguration"></param>
 /// <returns></returns>
 public static ReloadableLogger CreateBootstrapLogger(this LoggerConfiguration loggerConfiguration)
 {
     return(new ReloadableLogger(loggerConfiguration.CreateLogger()));
 }
Example #39
0
        /// <summary>Sets Serilog as the logging provider.</summary>
        /// <remarks>
        /// A <see cref="HostBuilderContext"/> is supplied so that configuration and hosting information can be used.
        /// The logger will be shut down when application services are disposed.
        /// </remarks>
        /// <param name="builder">The host builder to configure.</param>
        /// <param name="configureLogger">The delegate for configuring the <see cref="Serilog.LoggerConfiguration" /> that will be used to construct a <see cref="Serilog.Core.Logger" />.</param>
        /// <param name="preserveStaticLogger">Indicates whether to preserve the value of <see cref="Serilog.Log.Logger"/>.</param>
        /// <param name="writeToProviders">By default, Serilog does not write events to <see cref="ILoggerProvider"/>s registered through
        /// the Microsoft.Extensions.Logging API. Normally, equivalent Serilog sinks are used in place of providers. Specify
        /// <c>true</c> to write events to all providers.</param>
        /// <remarks>If the static <see cref="Log.Logger"/> is a bootstrap logger (see
        /// <c>LoggerConfigurationExtensions.CreateBootstrapLogger()</c>), and <paramref name="preserveStaticLogger"/> is
        /// not specified, the the bootstrap logger will be reconfigured through the supplied delegate, rather than being
        /// replaced entirely or ignored.</remarks>
        /// <returns>The host builder.</returns>
        public static IHostBuilder UseSerilog(
            this IHostBuilder builder,
            Action <HostBuilderContext, IServiceProvider, LoggerConfiguration> configureLogger,
            bool preserveStaticLogger = false,
            bool writeToProviders     = false)
        {
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }
            if (configureLogger == null)
            {
                throw new ArgumentNullException(nameof(configureLogger));
            }

            // This check is eager; replacing the bootstrap logger after calling this method is not supported.
#if !NO_RELOADABLE_LOGGER
            var reloadable = Log.Logger as ReloadableLogger;
            var useReload  = reloadable != null && !preserveStaticLogger;
#else
            const bool useReload = false;
#endif

            builder.ConfigureServices((context, collection) =>
            {
                LoggerProviderCollection loggerProviders = null;
                if (writeToProviders)
                {
                    loggerProviders = new LoggerProviderCollection();
                }

                collection.AddSingleton(services =>
                {
                    ILogger logger;
#if !NO_RELOADABLE_LOGGER
                    if (useReload)
                    {
                        reloadable !.Reload(cfg =>
                        {
                            if (loggerProviders != null)
                            {
                                cfg.WriteTo.Providers(loggerProviders);
                            }

                            configureLogger(context, services, cfg);
                            return(cfg);
                        });

                        logger = reloadable.Freeze();
                    }
                    else
#endif
                    {
                        var loggerConfiguration = new LoggerConfiguration();

                        if (loggerProviders != null)
                        {
                            loggerConfiguration.WriteTo.Providers(loggerProviders);
                        }

                        configureLogger(context, services, loggerConfiguration);
                        logger = loggerConfiguration.CreateLogger();
                    }

                    return(new RegisteredLogger(logger));
                });

                collection.AddSingleton(services =>
                {
                    // How can we register the logger, here, but not have MEDI dispose it?
                    // Using the `NullEnricher` hack to prevent disposal.
                    var logger = services.GetRequiredService <RegisteredLogger>().Logger;
                    return(logger.ForContext(new NullEnricher()));
                });

                collection.AddSingleton <ILoggerFactory>(services =>
                {
                    var logger = services.GetRequiredService <RegisteredLogger>().Logger;

                    ILogger registeredLogger = null;
                    if (preserveStaticLogger)
                    {
                        registeredLogger = logger;
                    }
                    else
                    {
                        // Passing a `null` logger to `SerilogLoggerFactory` results in disposal via
                        // `Log.CloseAndFlush()`, which additionally replaces the static logger with a no-op.
                        Log.Logger = logger;
                    }

                    var factory = new SerilogLoggerFactory(registeredLogger, !useReload, loggerProviders);

                    if (writeToProviders)
                    {
                        foreach (var provider in services.GetServices <ILoggerProvider>())
                        {
                            factory.AddProvider(provider);
                        }
                    }

                    return(factory);
                });

                // Null is passed here because we've already (lazily) registered `ILogger`
                ConfigureServices(collection, null);
            });

            return(builder);
        }
Example #40
0
        public SerilogLoggingScope(IConfiguration cfg, string scopeName, Type typeDef)
        {
            this._cfg       = cfg;
            this.ScopeName  = scopeName;
            this.typeDef    = typeDef;
            this._stopwatch = new System.Diagnostics.Stopwatch();
            _stopwatch.Start();
            bool useEventLog    = false;
            var  eventLogSource = _cfg.ApplicationName;
            bool useConsole     = true;

            // Some defaults
            try
            {
                defaultProps.Add("Scope", scopeName);
                defaultProps.Add("Type", typeDef);

                // Parse from scopeData object?
            }
            catch (Exception)
            {
                // Swallow
            }
            this._defaultEnrichers = new List <ILogEventEnricher>
            {
                new SecureBootstrapConfigurationEnricher(this._cfg),
                //new PropsDictionaryEnricher(defaultProps),
            };

            this._levelSwitch.MinimumLevel = Serilog.Events.LogEventLevel.Debug;

            var loggerCfg = new Serilog.LoggerConfiguration()
                            .ReadFrom.AppSettings()
                            .Destructure.ToMaximumDepth(3)
                            .MinimumLevel.ControlledBy(_levelSwitch)
                            .Enrich.FromLogContext()
                            .Enrich.WithMachineName()
                            //.Enrich.WithEnvironment("")
                            //.Enrich.With<SourceSystemEnricher<SerilogLoggingScope>>()
                            //.Enrich.With<SourceSystemInformationalVersionEnricher<SerilogLoggingScope>>()
                            .Enrich.With(_defaultEnrichers.ToArray())
                            //.Enrich.WithProcessId()
                            //.Enrich.WithProcessName()
            ;

            //if (!string.IsNullOrEmpty(_cfg.LoggingServerConnectionString))
            //{
            //    loggerCfg.WriteTo.Seq(_cfg.LoggingServerConnectionString, compact: true, controlLevelSwitch: _levelSwitch);
            //}
            //if (useEventLog)
            //{
            //    loggerCfg.WriteTo.EventLog(eventLogSource,
            //            outputTemplate: "C:{AXCompanyCode}-{User}{NewLine}{Message}{NewLine}{SessionId} - {CorrelationId} - {SourceContext}{NewLine}{Exception}",
            //            restrictedToMinimumLevel: Serilog.Events.LogEventLevel.Warning);
            //}
            if (useConsole)
            {
                loggerCfg.WriteTo.Console();
            }

            _logger = loggerCfg
                      .CreateLogger();
        }
Example #41
0
        public SerilogLogger(LogConfig logConfig, IReflection reflection)
        {
            Argument.NotNull(() => logConfig);
            Argument.NotNull(() => reflection);

            this.EnableVerbose = logConfig.Verbose;

            CreateLogsDirectory();

            var loggerConfig = new Serilog.LoggerConfiguration();

            if (this.EnableVerbose)
            {
                loggerConfig = loggerConfig.MinimumLevel.Verbose();
            }

            loggerConfig = loggerConfig.WriteTo.Trace();

            var emptyTypeArray   = new Type[0];
            var emptyObjectArray = new object[0];

            var logEnrichers = reflection.FindTypesMarkedByAttributes(LinqExts.FromItems(typeof(LogEnricherAttribute)));

            loggerConfig = logEnrichers
                           .Select(logEnricherType => logEnricherType.GetConstructor(emptyTypeArray).Invoke(emptyObjectArray))
                           .Cast <Serilog.Core.ILogEventEnricher>()
                           .Aggregate(loggerConfig, (prevLoggerConfig, logEnricher) => prevLoggerConfig.Enrich.With(logEnricher));

            if (logsDirectoryStatus == LogsDirectoryStatus.Created)
            {
                loggerConfig.WriteTo.File(Path.Combine(LogsDirectoryPath, "Errors.log"), LogEventLevel.Error);
                loggerConfig.WriteTo.File(Path.Combine(LogsDirectoryPath, "Info.log"), LogEventLevel.Information);
                loggerConfig.WriteTo.File(Path.Combine(LogsDirectoryPath, "Verbose.log"), LogEventLevel.Verbose);
            }

            if (!string.IsNullOrEmpty(logConfig.LogPostUrl))
            {
                Debug.Log("Sending log messages via HTTP to " + logConfig.LogPostUrl);

                loggerConfig.WriteTo.Sink(new SerilogHttpSink(logConfig.LogPostUrl));
            }
            else
            {
                Debug.Log("Not sending log messages via HTTP");
            }

            foreach (var sinkType in reflection.FindTypesMarkedByAttributes(LinqExts.FromItems(typeof(SerilogSinkAttribute))))
            {
                loggerConfig.WriteTo.Sink((Serilog.Core.ILogEventSink)sinkType.GetConstructor(emptyTypeArray).Invoke(emptyObjectArray));
            }

            this.serilog = loggerConfig.CreateLogger();

            LogInfo("Application started at {TimeNow}", DateTime.Now);
            LogInfo("Logs directory status: {LogsDirectoryStatus}", logsDirectoryStatus);
            if (logsDirectoryStatus == LogsDirectoryStatus.Failed)
            {
                LogError(logsDirectoryCreateException, "Failed to create logs directory {LogsDirectoryPath}", LogsDirectoryPath);
            }
            else
            {
                LogInfo("Writing logs and reports to {LogsDirectoryPath}", LogsDirectoryPath);
            }

            if (this.EnableVerbose)
            {
                LogInfo("Verbose logging is enabled.");
            }
            else
            {
                LogInfo("Verbose logging is not enabled.");
            }

            LogSystemInfo();

            DeleteOldLogFiles();

            // Initialize errors for unhandled promises.
            Promise.UnhandledException += (s, e) => LogError(e.Exception, "Unhandled error from promise.");

            Application.RegisterLogCallbackThreaded((msg, stackTrace, type) =>
            {
                if (!msg.StartsWith(SerilogUnitySink.RSGLogTag))
                {
                    switch (type)
                    {
                    case LogType.Assert:
                    case LogType.Error:
                    case LogType.Exception: LogError(msg + "\r\nStack:\r\n{StackTrace}", stackTrace); break;

                    case LogType.Warning: LogWarning(msg + "\r\nStack:\r\n{StackTrace}", stackTrace); break;

                    default: LogInfo(msg + "\r\nStack:\r\n{StackTrace}", stackTrace); break;
                    }
                }
            });
        }
		private static void ConfigureLogging(bool isEnableVerbose = false)
		{
			var loggingConfig = new LoggerConfiguration().WriteTo.ColoredConsole();

		    if (isEnableVerbose)
		    {
		        loggingConfig.MinimumLevel.Verbose();
		    }
		    else
		    {
                loggingConfig.MinimumLevel.Warning();
            }

		    if (!string.IsNullOrEmpty(StaticConfiguration.LoggingEndpoint))
			{
				loggingConfig.WriteTo.Seq(StaticConfiguration.LoggingEndpoint);
			}

			Log.Logger=loggingConfig.CreateLogger();
		}
        /// <summary>
        /// Creates a logger for Serilog.
        /// </summary>
        private static Logger CreateLogger(IConfigurationRoot configurationRoot, Func<LogEvent, bool> includeLogEvent)
        {
            var loggerConfiguration = new LoggerConfiguration()
                .MinimumLevel.Debug()
                .Enrich.FromLogContext()
                .Enrich.With(new AsyncFriendlyStackTraceEnricher());

            // Always write to the console
            loggerConfiguration.WriteTo.ColoredConsole();

            // Write to disk if requested
            var rollingFilePath = configurationRoot["RollingLogPath"];
            if (rollingFilePath != null)
            {
                loggerConfiguration.WriteTo.RollingFile(rollingFilePath);
            }

            // Write to application insights if requested

            var appInsightsKey = configurationRoot.GetSection("ApplicationInsights")
                ?["InstrumentationKey"];

            if (appInsightsKey != null)
            {
                loggerConfiguration.WriteTo.ApplicationInsightsTraces
                (
                    appInsightsKey,
                    LogEventLevel.Information,
                    null /*formatProvider*/,
                    (logEvent, formatProvider) =>
                        ConvertLogEventsToCustomTraceTelemetry(logEvent, formatProvider, includeLogEvent)
                );
            }

            return loggerConfiguration.CreateLogger();
        }
        private ILogger CreateLogger(ISettings settings, string fileName = null, string tableName = null, ICollection<DataColumn> additionalColumns = null, bool? logToFile = null, bool? logToSql = null)
        {
            var logsPath = string.IsNullOrEmpty(Environment.GetEnvironmentVariable("WEBSITE_SITE_NAME"))
                ? HostingEnvironment.ApplicationPhysicalPath
                : Path.Combine(Environment.GetEnvironmentVariable("HOME"), "LogFiles");

            var logger = new LoggerConfiguration()
                .Enrich.With<HttpRequestIdEnricher>()
                .Enrich.With<UserNameEnricher>()
                .Enrich.With<EventIdEnricher>();

            if (logToFile ?? settings.LogToFile && !string.IsNullOrEmpty(fileName))
            {
                logger = logger.WriteTo.RollingFile(Path.Combine(logsPath, fileName), fileSizeLimitBytes: null);
            }

            if (logToSql ?? settings.LogToSql &&
                !string.IsNullOrEmpty(settings.LoggingSqlServerConnectionString) &&
                !string.IsNullOrEmpty(tableName))
            {
                var columnOptions = new ColumnOptions
                {
                    AdditionalDataColumns = new Collection<DataColumn>
                    {
                        new DataColumn {DataType = typeof(string), ColumnName = "UserName"},
                        new DataColumn {DataType = typeof(string), ColumnName = "HttpRequestId"},
                        new DataColumn {DataType = typeof(int), ColumnName = "EventId"}
                    }
                    .Union(additionalColumns ?? Enumerable.Empty<DataColumn>())
                    .ToList()
                };
                logger = logger.WriteTo.MSSqlServer(settings.LoggingSqlServerConnectionString, tableName, restrictedToMinimumLevel: LogEventLevel.Information, columnOptions: columnOptions);
            }
            return logger.CreateLogger();
        }
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            var config =
                new LoggerConfiguration()
                    .WriteTo.Seq(serverUrl: Configuration["Seq:Url"], apiKey: Configuration["Seq:Key"])
                    .Enrich.WithProperty("ApplicationName", "Music Store")
                    .Enrich.With(new HttpRequestIdEnricher());
            Log.Logger = config.CreateLogger();

            loggerFactory.AddSerilog();
            loggerFactory.AddDebug();

            if (env.IsDevelopment())
            {
                app.UseCors(policy => policy
                    .AllowAnyOrigin()
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials());
            }
            else
            {
                app.UseCors(policy => policy
                            .WithOrigins(Configuration["Cors:Url"])
                            .AllowAnyMethod()
                            .AllowAnyHeader()
                            .AllowCredentials());
            }

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            // required for decryption
            var keyAsBase64 = Configuration["Auth0:ClientSecret"].Replace('_', '/').Replace('-', '+');
            var keyAsBytes = Convert.FromBase64String(keyAsBase64);

            var jwtOptions = new JwtBearerOptions
            {
                Audience = Configuration["Auth0:ClientId"],
                Authority = $"https://{Configuration["Auth0:Domain"]}",
                Events = new JwtBearerEvents
                {
                    OnAuthenticationFailed = context =>
                    {
                        Log.Logger.Error("Authentication failed.", context.Exception);
                        return Task.FromResult(0);
                    }
                },
                TokenValidationParameters =
                {
                    IssuerSigningKey = new SymmetricSecurityKey(keyAsBytes)
                }
            };
            app.UseJwtBearerAuthentication(jwtOptions);

            // Note: this line must be after the OAuth config above
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "",
                    defaults: new { controller = "Home", action = "Index" }
                );
            });
            app.UseSwaggerUi();
            app.UseSwagger();

            app.UseRaygun();

            app.UseApplicationInsightsRequestTelemetry();
            app.UseApplicationInsightsExceptionTelemetry();
        }
Example #46
0
        public void Initialize()
        {
            // read the root folder for logs.
            _rootFolder = !string.IsNullOrEmpty(_config.Root) ? _config.Root : "logs";

            if (!Directory.Exists(_rootFolder)) // make sure log root exists.
                Directory.CreateDirectory(_rootFolder);

            // create the global logger.
            var globalConfig = new LoggerConfiguration();
            var packetLoggerConfig = new LoggerConfiguration();

            // add enrichers
            globalConfig.Enrich.With(new SourceEnricher());
            globalConfig.Enrich.With(new ComponentEnricher());

            packetLoggerConfig.Enrich.With(new SourceEnricher());
            packetLoggerConfig.Enrich.With(new ComponentEnricher());

            foreach (var target in _config.Targets)
            {
                switch (target.Type)
                {
                    case LogTargetType.Console:
                        CreateConsoleLog(globalConfig, target);
                        break;
                    case LogTargetType.File:
                        CreateFileLog(globalConfig, target);
                        break;
                    case LogTargetType.Packet:
                        CreatePacketLog(packetLoggerConfig, target);
                        break;
                }
            }

            // lower the default minimum level to verbose as sinks can only rise them but not lower.
            globalConfig.MinimumLevel.Verbose();
            packetLoggerConfig.MinimumLevel.Verbose();

            Log.Logger = globalConfig.CreateLogger(); // bind the config to global log.
            PacketLogger = packetLoggerConfig.CreateLogger();
        }
Example #47
0
        /// <summary>
        ///  Dependency injection configuration
        /// </summary>
        /// <param name="container">Dependency injection container</param>
        /// <param name="args">
        /// Startup parameters
        /// </param>
        /// <returns>The actor system</returns>
        public static ActorSystem ConfigureAndStart(IWindsorContainer container, string[] args)
        {
            Console.WriteLine(@"Starting bootstrapper");

            container.AddFacility<TypedFactoryFacility>();
            container.Kernel.Resolver.AddSubResolver(new ArrayResolver(container.Kernel, true));
            container.Register(Component.For<IWindsorContainer>().Instance(container));

            container.RegisterWindsorInstallers();

            Console.WriteLine(@"Preparing config");
            var config = BaseInstaller.GetStackedConfig(container, CreateTopLevelConfig(args));

            Log.Debug($"Cluster configuration: seed-nodes { string.Join(", ", config.GetStringList("akka.cluster.seed-nodes") ?? new List<string>())}");
            Log.Debug($"Cluster configuration: min-nr-of-members { config.GetInt("akka.cluster.min-nr-of-members")}");
            var roles = string.Join(", ", config.GetStringList("akka.cluster.roles") ?? new List<string>());
            Log.Debug($"Cluster configuration: roles { roles}");
            Log.Debug($"Cluster node hostname: { config.GetString("akka.remote.helios.tcp.hostname") }");
            var publicHostName = config.GetString("akka.remote.helios.tcp.public-hostname");
            if (!string.IsNullOrWhiteSpace(publicHostName))
            {
                Log.Debug($"Cluster node public hostname: { publicHostName }");
            }

            container.Register(Component.For<Config>().Instance(config));
            Console.WriteLine(@"Config created");

            // log configuration
            LogEventLevel level;
            if (!Enum.TryParse(config.GetString("ClusterKit.Log.minimumLevel"), true, out level))
            {
                level = LogEventLevel.Information;
            }

            var loggerConfig = new LoggerConfiguration().MinimumLevel.Is(level);
            var configurators = container.ResolveAll<ILoggerConfigurator>();

            configurators.ForEach(c => Log.Information("Using log configurator {TypeName}", c.GetType().FullName));

            loggerConfig = configurators.Aggregate(
                loggerConfig,
                (current, loggerConfigurator) => loggerConfigurator.Configure(current, config));

            var hostName = string.IsNullOrWhiteSpace(publicHostName)
                               ? config.GetString("akka.remote.helios.tcp.hostname")
                               : publicHostName;

            loggerConfig = loggerConfig.Enrich.WithProperty("hostName", hostName);
            loggerConfig = loggerConfig.Enrich.WithProperty("roles", roles);

            var logger = loggerConfig.CreateLogger();
            Log.Logger = logger;

            // log configuration finished

            // performing prestart checks
            BaseInstaller.RunPrecheck(container, config);

            // starting Akka system
            Console.WriteLine(@"starting akka system");
            var actorSystem = ActorSystem.Create("ClusterKit", config);
            actorSystem.AddDependencyResolver(new WindsorDependencyResolver(container, actorSystem));

            container.Register(Component.For<ActorSystem>().Instance(actorSystem).LifestyleSingleton());
            ServiceLocator.SetLocatorProvider(() => new WindsorServiceLocator(container));

            Console.WriteLine(@"Bootstrapper start finished");

            return actorSystem;
        }
Example #48
0
        /// <summary>
        /// The program's Main is an <see langword="async"/> Task . Entry point to the Program
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>

        public static async Task Main(string[] args)
        {
            #region Startup logger
            // Configure a startup logger, prior to getting the Logger configuration from the ConfigurationRoot
            // Serilog is the logging provider I picked to provide a logging solution for the Console01 application
            // Enable Serilog's internal debug logging. Note that internal logging will not write to any user-defined Sources
            //  https://github.com/serilog/serilog-sinks-file/blob/dev/example/Sample/Program.cs
            Serilog.Debugging.SelfLog.Enable(System.Console.Out);
            // Another example is at https://stackify.com/serilog-tutorial-net-logging/
            //  This brings in the System.Diagnostics.Debug namespace and writes the SelfLog there
            Serilog.Debugging.SelfLog.Enable(msg => Debug.WriteLine(msg));
            Serilog.Debugging.SelfLog.WriteLine("in Program.Main(Serilog Self Log)");
            // Another example is at https://github.com/serilog/serilog-extensions-logging/blob/dev/samples/Sample/Program.cs
            // Another is https://nblumhardt.com/2019/10/serilog-in-aspnetcore-3/
            // Creating a `LoggerProviderCollection` lets Serilog optionally write events through other dynamically-added MEL ILoggerProviders.
            //var providers = new LoggerProviderCollection();
            // Setup Serilog's static logger with an initial configuration sufficient to log startup errors

            // create a local Serilog logger for use during Program startup
            var serilogLoggerConfiguration = new Serilog.LoggerConfiguration()
                                             .MinimumLevel.Verbose()
                                             .Enrich.FromLogContext()
                                             .Enrich.WithThreadId()
                                             .WriteTo.Console(outputTemplate: "Static startup Serilog {Timestamp:HH:mm:ss zzz} [{Level}] ({Name:l}) {Message}{NewLine}{Exception}")
                                             .WriteTo.Seq(serverUrl: "http://*****:*****@"C:\Dropbox\whertzing\GitHub\ATAP.Utilities\devlog\A01Console.{Date}.log", fileSizeLimitBytes: 1024, outputTemplate: "Static Serilog {Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] {Message}{NewLine}{Exception}", rollingInterval: RollingInterval.Day, rollOnFileSizeLimit: true, retainedFileCountLimit: 31)
                                             .WriteTo.Debug();
            //.Enrich.WithHttpRequestId()
            //.Enrich.WithUserName()
            //.WithExceptionDetails()
            //.WriteTo.Providers(providers)

            Serilog.Core.Logger serilogLogger = serilogLoggerConfiguration.CreateLogger();
            // Set the Static logger called Log to use this LoggerConfiguration
            Serilog.Log.Logger = serilogLogger;
            Log.Debug("{Program} {Main}: The program Console01 is starting", "Program", "Main");
            Log.Debug("{Program} {Main}: LoggerFactory and local logger defined with a default startup configuration:", "Program", "Main");

            // Set the MEL LoggerFactory to use this LoggerConfiguration
            Microsoft.Extensions.Logging.ILoggerFactory mELoggerFactory = new Microsoft.Extensions.Logging.LoggerFactory().AddSerilog();
            Microsoft.Extensions.Logging.ILogger        mELlogger       = mELoggerFactory.CreateLogger("Program");
            mELlogger.LogDebug("{0} {1}: The program Console01 is starting", "Program", "Main");
            mELlogger.LogDebug("{0} {1}: LoggerFactory and local logger defined with a default startup configuration:", "Program", "Main");
            #endregion

            #region stringLocalizers and optionally resource managers for InternationalizatioN (AKA I18N)
            // populate the string localizers for Program
            Options = Microsoft.Extensions.Options.Options.Create(new LocalizationOptions());
            StringLocalizerFactory = new ResourceManagerStringLocalizerFactory(Options, NullLoggerFactory.Instance);
            DebugLocalizer         = StringLocalizerFactory.Create(nameof(Resources), "ATAP.Console.Console01");
            ExceptionLocalizer     = StringLocalizerFactory.Create(nameof(Resources), "ATAP.Console.Console01");
            ConfigLCL   = StringLocalizerFactory.Create(nameof(Resources), "ATAP.Console.Console01");
            UILocalizer = StringLocalizerFactory.Create(nameof(Resources), "ATAP.Console.Console01");

            // If localized non-string resources are needed, uncomment the following block
            // Load the ResourceManagers from the installation directory. These provide access to all localized resources including non-string resources
            // Cannot create more-derived types from a ResourceManager. Gets Invalid cast. See also https://stackoverflow.com/questions/2500280/invalidcastexception-for-two-objects-of-the-same-type/30623970, the invalid cast might be because ResourceManagers are not per-assembly?
            // i.e., the following will no compile DebugResourceManager debugResourceManager = (DebugResourceManager)new ResourceManager("ATAP.Console.Console01.Properties.ConsoleDebugResources", typeof(ConsoleDebugResources).Assembly);
            // These will compile if needed
            //var debugResourceManager = new ResourceManager("ATAP.Console.Console01.Properties.ConsoleDebugResources", typeof(ConsoleDebugResources).Assembly);
            //var exceptionResourceManager = new ResourceManager("ATAP.Console.Console01.Properties.ConsoleExceptionResources", typeof(ConsoleExceptionResources).Assembly);
            //var uIResourceManager = new ResourceManager("ATAP.Console.Console01.Properties.ConsoleUIResources", typeof(ConsoleUIResources).Assembly);
            #endregion region

            #region initialStartup and loadedFrom directories
            // When running as a Windows service, the initial working dir is usually %WinDir%\System32, but the program (and configuration files) is probably installed to a different directory
            // When running as a *nix service, the initial working dir could be anything. The program (and machine-wide configuration files) are probably installed in the location where the service starts. //ToDo: verify this
            // When running as a Windows or Linux Console App, the initial working dir could be anything, but the program (and machine-wide configuration files) is probably installed to a different directory.
            // When running as a console app, it is very possible that there may be local (to the initial startup directory) configuration files to load
            // get the initial startup directory
            // get the directory where the executing assembly (usually .exe) and possibly machine-wide configuration files are installed to.
            var initialStartupDirectory = Directory.GetCurrentDirectory();                             //ToDo: Catch exceptions
            mELlogger.LogDebug(DebugLocalizer["{0} {1}: initialStartupDirectory: {2}", "Program", "Main", initialStartupDirectory]);
            var loadedFromDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); //ToDo: Catch exceptions
            mELlogger.LogDebug(DebugLocalizer["{0} {1}: loadedFromDirectory: {2}", "Program", "Main", loadedFromDirectory]);
            #endregion region

            #region initial genericHostConfigurationBuilder and genericHostConfigurationRoot
            // Create the initial genericHostConfigurationBuilder for this genericHost's ConfigurationRoot. This creates an ordered chain of configuration providers. The first providers in the chain have the lowest priority, the last providers in the chain have a higher priority.
            // Initial configuration does not take Environment into account.
            var genericHostConfigurationBuilder = ConfigurationExtensions.ATAPStandardConfigurationBuilder(
                GenericHostDefaultConfiguration.Production, true, null, GenericHostStringConstants.genericHostSettingsFileName,
                GenericHostStringConstants.hostSettingsFileNameSuffix, loadedFromDirectory, initialStartupDirectory, hostEnvPrefixes, args, switchMappings);

            // Create this program's initial genericHost's ConfigurationRoot
            var genericHostConfigurationRoot = genericHostConfigurationBuilder.Build();
            #endregion

            #region (optional) Debugging the  Configuration
            // for debugging and education, uncomment this region and inspect the two section Lists (using debugger Locals) to see exactly what is in the configuration
            //    var sections = genericHostConfigurationRoot.GetChildren();
            //    List<IConfigurationSection> sectionsAsListOfIConfigurationSections = new List<IConfigurationSection>();
            //    List<ConfigurationSection> sectionsAsListOfConfigurationSections = new List<ConfigurationSection>();
            //    foreach (var iSection in sections) sectionsAsListOfIConfigurationSections.Add(iSection);
            //    foreach (var iSection in sectionsAsListOfIConfigurationSections) sectionsAsListOfConfigurationSections.Add((ConfigurationSection)iSection);
            #endregion

            #region Environment determination and validation
            // ToDo: Before the genericHost is built, have to use a StringConstant for the string that means "Production", and hope the ConfigurationRoot value for Environment matches the StringConstant
            // Determine the environment (Debug, TestingUnit, TestingX, QA, QA1, QA2, ..., Staging, Production) to use from the initialGenericHostConfigurationRoot
            var envNameFromConfiguration = genericHostConfigurationRoot.GetValue <string>(GenericHostStringConstants.EnvironmentConfigRootKey, GenericHostStringConstants.EnvironmentDefault);
            mELlogger.LogDebug(DebugLocalizer["{0} {1}: Initial environment name: {2}", "Program", "Main", envNameFromConfiguration]);

            // optional: Validate that the environment provided is one this program understands how to use
            // Accepting any string for envNameFromConfiguration might pose a security risk, as it will allow arbitrary files to be loaded into the configuration root
            switch (envNameFromConfiguration)
            {
            case GenericHostStringConstants.EnvironmentDevelopment:
                // ToDo: Programmers can add things here
                break;

            case GenericHostStringConstants.EnvironmentProduction:
                // This is the expected leg for Production environment
                break;

            default:
                // IF you want to accept any environment name as OK, just comment out the following throw
                // Keep the throw in here if you want to explicitly disallow any environment other than ones specified in the switch
                throw new NotImplementedException(ExceptionLocalizer["The Environment {0} is not supported", envNameFromConfiguration]);
            }
            ;
            #endregion

            #region final (Environment-aware) genericHostConfigurationBuilder and appConfigurationBuilder
            // If the initial genericHostConfigurationRoot specifies the Environment is production, then the genericHostConfigurationBuilder is correct  "as-is"
            //   but if not, build a 2nd (final) genericHostConfigurationBuilder, this time including environment-specific configuration providers
            if (envNameFromConfiguration != GenericHostStringConstants.EnvironmentProduction)
            {
                // Recreate the ConfigurationBuilder for this genericHost, this time including environment-specific configuration providers.
                mELlogger.LogDebug(DebugLocalizer["{0} {1}: Recreating genericHostConfigurationBuilder for Environment: {2}"], "Program", "Main", envNameFromConfiguration);
                genericHostConfigurationBuilder = ConfigurationExtensions.ATAPStandardConfigurationBuilder(GenericHostDefaultConfiguration.Production, false, envNameFromConfiguration,
                                                                                                           GenericHostStringConstants.genericHostSettingsFileName, GenericHostStringConstants.hostSettingsFileNameSuffix, loadedFromDirectory, initialStartupDirectory, hostEnvPrefixes, args, switchMappings);
            }

            // Create the appConfigurationBuilder, either as Production or as some other environment specific
            IConfigurationBuilder appConfigurationBuilder;
            mELlogger.LogDebug(DebugLocalizer["{0} {1}: Creating appConfigurationBuilder for Environment: {2}"], "Program", "Main", envNameFromConfiguration);
            appConfigurationBuilder = ConfigurationExtensions.ATAPStandardConfigurationBuilder(Console01DefaultConfiguration.Production, envNameFromConfiguration == GenericHostStringConstants.EnvironmentProduction, envNameFromConfiguration,
                                                                                               Console01StringConstants.SettingsFileName, Console01StringConstants.SettingsFileNameSuffix, loadedFromDirectory, initialStartupDirectory, appEnvPrefixes, args, switchMappings);
            #endregion


            #region Configure the genericHostBuilder, including DI-Container, IHostLifetime, services in the services collection, genericHostConfiguration, and appConfiguration

            // Make a GenericHostBuilder with the Configuration (as above), and chose a specific instance of an IHostLifetime
            var genericHostBuilder = GenericHostExtensions.ATAPStandardGenericHostBuilderForConsoleLifetime(genericHostConfigurationBuilder, appConfigurationBuilder);

            // Add the specific IHostLifetime for this program (or service)
            //ToDo: implement service and serviced, then see if this can be moved to the ATAPStandardGenericHostBuilder static extension method
            genericHostBuilder.ConfigureServices((hostContext, services) => {
                services.AddSingleton <IHostLifetime, ConsoleLifetime>();
                //services.AddOptions<ConsoleLifetime>(Options => Options.SuppressStatusMessages = true);
            });

            // in Production, surpress the startup messages appearing on the Console stdout
            if (envNameFromConfiguration == GenericHostStringConstants.EnvironmentProduction)
            {
                //genericHostBuilder.Configure<ConsoleLifetimeOptions>(Options => Options.SuppressStatusMessages = true); //
            }

            #region Configure the GenericHost logging per the Logging section in ConfigurationRoot
            genericHostBuilder.ConfigureLogging((hostContext, loggingBuilder) => {
                loggingBuilder.AddConfiguration(genericHostConfigurationRoot.GetSection("Logging"));
                //loggingBuilder.UseSerilog
            });
            // Build the GH configuration
            //genericHostConfigurationRoot = genericHostConfigurationBuilder.Build();
            //// Create a LoggerFactory, configure it to use Serilog
            //loggerConfiguration = genericHostConfigurationRoot.GetSection("Logging");
            //// redefine the factory according to the new configuration
            //factory = new LoggerFactory();
            //factory.AddSerilog(loggerConfiguration.CreateLogger());
            //// Set the LogFactory in the ATP.Utilities.Logging class
            //LogProvider.SetLogFactory(factory);
            //// Set the LogFactory in the DI-Services
            //// ToDo: LoggerFactory loggerFactory.SetLogFactory(factory);
            //// redefine the local logger from this factory, configured with the startup logging as defined in the Logging section of the configurationRoot
            //logger = factory.CreateLogger("Console01");
            //serilogLogger.LogDebug(DebugLocalizer["{0} {1}: LoggerFactory and local logger redefined per the Logging section in the configuration settings:"], "Program", "Main");
            //// Copy this tour "standard logger
            //// Create a LoggerFactory, configure it to use Serilog
            //var factory = new LoggerFactory();
            //var x = serilogLoggerConfiguration..CreateLoggerF();
            //factory.AddSerilog(serilogLoggerConfiguration.CreateLogger());
            //LogProvider.SetLogFactory(factory);
            //// Create a local logger from this factory, configured with the startup logging defined above
            //logger = factory.CreateLogger("Console01");
            //// For this program, I've selected Serilog as the underlying serilogLogger.
            //genericHostBuilder.UseSerilog();
            #endregion

            // Add specific services for this application
            genericHostBuilder.ConfigureServices((hostContext, services) => {
                // Localization for the services
                services.AddLocalization(options => options.ResourcesPath = "Resources");
                services.AddSingleton <IConsoleSinkHostedService, ConsoleSinkHostedService>();
                services.AddSingleton <IConsoleSourceHostedService, ConsoleSourceHostedService>();
                //services.AddHostedService<ConsoleMonitorBackgroundService>(); // Only use this service in a GenericHost having a DI-injected IHostLifetime of type ConsoleLifetime.
                services.AddHostedService <Console01BackgroundService>(); // Only use this service in a GenericHost having a DI-injected IHostLifetime of type ConsoleLifetime.
                //services.AddSingleton<IFileSystemWatchersHostedService, FileSystemWatchersHostedService>();
                services.AddSingleton <IObservableResetableTimersHostedService, ObservableResetableTimersHostedService>();
                //services.AddSingleton<IFileSystemWatchersAsObservableFactoryService, FileSystemWatchersAsObservableFactoryService>();
            });
            #endregion

            // Build the Host
            var genericHost = genericHostBuilder.Build();

            // Use the ConfigurationSettings for ConsoleLifetimeOptions.SuppressStatusMessages
            //services.Configure<ConsoleLifetimeOptions>(opts opts.SuppressStatusMessages = Configuration["SuppressStatusMessages"] != null)

            // Start it going
            try {
                mELlogger.LogDebug(DebugLocalizer["{0} {1}: \"using\" the genericHost.", "Program", "Main"]);
                using (genericHost) {
                    mELlogger.LogDebug(DebugLocalizer["{0} {1}: Calling StartAsync on the genericHost.", "Program", "Main"]);

                    // Start the generic host running all its services and setup listeners for stopping
                    // all the rigamarole in https://andrewlock.net/introducing-ihostlifetime-and-untangling-the-generic-host-startup-interactions/

                    // Attribution to https://stackoverflow.com/questions/52915015/how-to-apply-hostoptions-shutdowntimeout-when-configuring-net-core-generic-host for OperationCanceledException notes
                    // ToDo: further investigation to ensure OperationCanceledException should be ignored in all cases (service or console host, kestrel or IntegratedIISInProcessWebHost)
                    try {
                        // The RunAsync method exists on a genericHost instance having a DI container instance that resolves a IHostLifetime. There are three "standard" implementations of IHostLifetime, Console, Service (Windows) and Serviced (*nix)
                        // await genericHost.RunAsync().ConfigureAwait(false);
                        // From MSMQ process sample at https://github.com/dotnet/extensions/blob/master/src/Hosting/samples/SampleMsmqHost/Program.cs
                        // start the genericHost
                        await genericHost.StartAsync().ConfigureAwait(false);

                        //ToDo: Better understanding - should the primary BackgroundService be run here instead of as a Background service?

                        // Nothing to do, the HostedServices and BackgroundServices do it all
                        ////// ToDo:  Deal with application lifetime? can applications stop, and restart, within the lifetime of the genericHost
                        //////// Get the CancellationToken stored in IHostApplicationLifetime ApplicationStopping
                        ////// var applicationLifetime = genericHost.Services.GetRequiredService<IHostApplicationLifetime>();
                        ////// var cT = applicationLifetime.ApplicationStopping;
                        //////// hang out until cancellation is requested
                        //////while (!cT.IsCancellationRequested) {
                        //////  cT.ThrowIfCancellationRequested();
                        //////}
                        // wait for the genericHost to shutdown
                        await genericHost.WaitForShutdownAsync().ConfigureAwait(false);
                    }
                    catch (OperationCanceledException e) {
                        ; // Just ignore OperationCanceledException to suppress it from bubbling upwards if the main program was cancelledOperationCanceledException
                          // The Exception should be shown in the ETW trace
                          //ToDo: Add Error level or category to ATAPUtilitiesETWProvider, and make OperationCanceled one of the catagories
                          // Specifically log the details of the cancellation (where it originated)
                          // ATAPUtilitiesETWProvider.Log.Information($"Exception in Program.Main: {e.Exception.GetType()}: {e.Exception.Message}");
                    } // Other kinds of exceptions bubble up to the catch block for the surrounding try, where the Serilog logger records it
                    finally {
                        // Dispose of any resources held directly by this program. Resources held by services in the DI-Container will be disposed of by the genericHost as it tears down
                        //if (DisposeThis != null) { DisposeThis.Dispose(); }
                    }

                    // Here, the StartAsync has completed, the Main method is over
                    // Log Program finishing to ETW if it happens to resume execution here for some reason(as of 06/2019, ILWeaving this assembly results in a thrown invalid CLI Program Exception
                    // ATAP.Utilities.ETW.ATAPUtilitiesETWProvider.Log(">Program.Main");
                    mELlogger.LogDebug(DebugLocalizer["{0} {1}: the genericHost has exitied "], "Program", "Main");
                }
            }
            catch (Exception ex) {
                MELLogger.LogCritical(ExceptionLocalizer["{0} {1}: genericHost start-up failed. ExceptionMessage: {2}", "Program", "Main", ex.Message]);
                throw ex;
            }
            finally {
                // ToDo: How to do something similar for MEL logger?
                Log.CloseAndFlush();
            }

            #region Playing with CSharpSyntaxTree
            // Just playing with the CSharpSyntaxTree feature here
            //SyntaxTree tree = CSharpSyntaxTree.ParseText(programText);
            //CompilationUnitSyntax root = tree.GetCompilationUnitRoot();
            // Use the debugger and Locals window to see these objects
            #endregion region
            mELlogger.LogDebug(DebugLocalizer["{0} {1}: Program:Main is exiting", "Program", "Main"]);
        }