Configuration object for creating ILogger instances.
Exemple #1
1
        /// <summary>
        /// Performs configuration
        /// </summary>
        /// <param name="configuration">Previous configuration</param>
        /// <param name="config">Akka configuration</param>
        /// <returns>Updated configuration</returns>
        public LoggerConfiguration Configure(LoggerConfiguration configuration, Config config)
        {
            var minimumLevel = config.GetString("ClusterKit.Log.ElasticSearch.minimumLevel", "none")?.Trim();

            LogEventLevel level;
            if (!Enum.TryParse(minimumLevel, true, out level))
            {
                return configuration;
            }

            var nodes = config.GetStringList("ClusterKit.Log.ElasticSearch.nodes");

            var indexFormat = config.GetString("ClusterKit.Log.ElasticSearch.indexFormat", "logstash-{0:yyyy.MM.dd}");

            Log.Information(
                "{Type}: \n\tMinimum level: {MinimumLevel}\n\tIndex format: {IndexFormat}\n\tNodes:\n\t\t{NodeList}\n",
                this.GetType().FullName,
                minimumLevel,
                indexFormat,
                string.Join("\n\t\t", nodes));


            SelfLog.Enable(Console.WriteLine);
            var options = new ElasticsearchSinkOptions(nodes.Select(s => new Uri(s)))
                              {
                                  MinimumLogEventLevel = level,
                                  AutoRegisterTemplate = true,
                                  IndexFormat = indexFormat
                              };

            return configuration.WriteTo.Elasticsearch(options);


        }
        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);
            }
        }
Exemple #3
0
        public void InitializeLogger()
        {
            ILogger logger;

            if (_settings.UseRollingFile)
            {
                logger = new Serilog.LoggerConfiguration().WriteTo.RollingFile(pathFormat: _settings.LogFilePath, outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}",
                                                                               fileSizeLimitBytes: _settings.MaxFileSize, retainedFileCountLimit: _settings.MaxDaysToKeepOldFiles)
                         .Enrich.WithThreadId()
                         .Enrich.FromLogContext()
                         .MinimumLevel.Is(_settings.MinLevel)
                         .CreateLogger();
            }
            else
            {
                logger = new Serilog.LoggerConfiguration().WriteTo.File(_settings.LogFilePath, outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}",
                                                                        fileSizeLimitBytes: _settings.MaxFileSize)
                         .Enrich.WithThreadId()
                         .Enrich.FromLogContext()
                         .MinimumLevel.Is(_settings.MinLevel)
                         .CreateLogger();
            }

            Logger     = logger;
            Log.Logger = logger;
        }
        //
        // This method is invoked when the application has loaded and is ready to run. In this 
        // method you should instantiate the window, load the UI into it and then make the window
        // visible.
        //
        // You have 17 seconds to return from this method, or iOS will terminate your application.
        //
        public override bool FinishedLaunching(UIApplication app, NSDictionary options)
        {
			Current = this;

			var log = new LoggerConfiguration().CreateLogger();

			log.Information("Loading");

            UIApplication.SharedApplication.StatusBarStyle = UIStatusBarStyle.LightContent;

            // create a new window instance based on the screen size
            window = new UIWindow(UIScreen.MainScreen.Bounds);

            // If you have defined a view, add it here:
            // window.RootViewController  = navigationController;

			var rootNavigationController = Utilities.BuildNavigationController();
            rootNavigationController.PushViewController(new ViewControllers.Login(), false);
            window.RootViewController = rootNavigationController;

            // make the window visible
            window.MakeKeyAndVisible();

            Utilities.SetTintColor();

            autoSuspendHelper.FinishedLaunching(app, options);

            return true;
        }
Exemple #5
0
        private Serilog.LoggerConfiguration Configure(LoggerConfiguration settings, EmailSettings emailSettings)
        {
            FolderManager.CheckAndCreateDirectory($@"{_path}\logs");

            var seriLogConfig = new Serilog.LoggerConfiguration()
                                .Enrich
                                .WithExceptionDetails();

            if (settings.EnableSerilogDebugger)
            {
                var file = File.CreateText($@"{_path}\logs\serilog.txt");
                Serilog.Debugging.SelfLog.Enable(TextWriter.Synchronized(file));
            }

            if (settings.EnableFile)
            {
                seriLogConfig.WriteTo.RollingFile($@"{_path}\logs\log-{{Date}}.txt");
            }

            if (settings.EnableEmail && emailSettings != null && !string.IsNullOrEmpty(settings.LoggingFromEmail) && !string.IsNullOrEmpty(settings.LoggingToEmail))
            {
                seriLogConfig.WriteTo.Email(fromEmail:         settings.LoggingFromEmail,
                                            toEmail:           settings.LoggingToEmail,
                                            mailServer:        emailSettings.Server,
                                            networkCredential: new NetworkCredential
                {
                    Domain   = emailSettings.Domain,
                    UserName = emailSettings.Username,
                    Password = emailSettings.Password
                },
                                            restrictedToMinimumLevel: LogEventLevel.Error);
            }

            return(seriLogConfig);
        }
        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;
        }
Exemple #7
0
 /// <summary>
 ///     Configura o Logger para escrever em: File.
 /// </summary>
 /// <param name="loggerConfiguration">LoggerConfiguration</param>
 /// <returns>Mesma instância de entrada.</returns>
 private static Serilog.LoggerConfiguration WriteToFile(Serilog.LoggerConfiguration loggerConfiguration)
 {
     return(loggerConfiguration
            .WriteTo.File(
                $"{Assembly.GetAssembly(typeof(Program)).Location}.log-.txt",
                rollingInterval: RollingInterval.Day));
 }
        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.");
        }
Exemple #9
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;
            }
        }
        public void BaseSetup()
        {
            LogOutput = new StringBuilder();
            Log = new LoggerConfiguration()
                .WriteTo.TextWriter(new StringWriter(LogOutput), outputTemplate: "[{Level}] {Message}{NewLine}{Exception}", formatProvider: new StringFormatter(null))
                .CreateLogger();

            RootResource rootDocument = Substitute.For<RootResource>();
            rootDocument.ApiVersion = "2.0";
            rootDocument.Version = "2.0";
            rootDocument.Links.Add("Tenants", "http://tenants.org");

            Repository = Substitute.For<IOctopusAsyncRepository>();
            Repository.Client.RootDocument.Returns(rootDocument);

            ClientFactory = Substitute.For<IOctopusClientFactory>();

            RepositoryFactory = Substitute.For<IOctopusAsyncRepositoryFactory>();
            RepositoryFactory.CreateRepository(null).ReturnsForAnyArgs(Repository);

            FileSystem = Substitute.For<IOctopusFileSystem>();

            CommandLineArgs = new List<string>
            {
                "--server=http://the-server",
                "--apiKey=ABCDEF123456789"
            };
        }
 public WorkflowRegistry()
 {
     For<IRepository<Crisis>>().Use<CrisisRepository>();
     var logFolder =  ConfigurationManager.AppSettings["LogFolder"] + @"\Log-{Date}.txt";
     var logger = new LoggerConfiguration().WriteTo.RollingFile(logFolder).CreateLogger();
     For<ILogger>().Use(x => 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> >();
        }
 /// <summary>
 /// Performs configuration
 /// </summary>
 /// <param name="configuration">Previous configuration</param>
 /// <param name="config">Akka configuration</param>
 /// <returns>Updated configuration</returns>
 public LoggerConfiguration Configure(LoggerConfiguration configuration, Config config)
 {
     var templateName = config.GetString("ClusterKit.NodeManager.NodeTemplate");
     return string.IsNullOrWhiteSpace(templateName)
                ? configuration
                : configuration.Enrich.WithProperty("nodeTemplate", templateName);
 }
        public static void SetupContainer()
        {
            // Create User
            var user = new CurrentUser() { Username = "******", LabCode = "EUHAWE3" };

            // Create Logger
            var logger = new LoggerConfiguration()
              .Enrich.FromLogContext()
                .MinimumLevel.Warning()                 // Set MinimumLevel of Warning
                .WriteTo.Seq("http://localhost:5341")
              .CreateLogger();

            unityContainer = new UnityContainer();

            // Register User
            unityContainer.RegisterInstance<ICurrentUser>(user);

            // Add Interception Extension
            unityContainer.AddNewExtension<Microsoft.Practices.Unity.InterceptionExtension.Interception>();

            //Register Logger Instance
            unityContainer.RegisterInstance<ILogger>(logger);

            unityContainer.RegisterType<ISamRepository, SamRepository>()
                .Configure<Microsoft.Practices.Unity.InterceptionExtension.Interception>()
                .SetInterceptorFor<ISamRepository>(
                    new InterfaceInterceptor());
        }
	    public OrleansTestActorService(StatelessServiceContext context)
		    : base(context)
	    {
		    var esLogsConfig = new FabricConfigProvider<ElasticSearchOutputConfig>("ElasticSearchLogs").Config;
			var esMetricsConfig = new FabricConfigProvider<ElasticSearchOutputConfig>("ElasticSearchMetrics").Config;

			var logger = new LoggerConfiguration()
				.MinimumLevel.Verbose()
				.Enrich.With(new AzureServiceFabricSerilogEnricher(context))
				.Enrich.With<ExceptionEnricher>()
				.Enrich.With<ActivityIdSerilogEnricher>()
				.WriteTo.Elasticsearch(
					new ElasticsearchSinkOptions(new Uri(esLogsConfig.ElasticSearchUri))
					{
						IndexFormat = $"{esLogsConfig.ElasticSearchIndexName}-{{0:yyyy.MM.dd}}"
					})
				.CreateLogger();
			Log.Logger = logger;

			
			//Metric.Config.WithAllCounters();

			_disposable = new TelemetryPipe()
				.CollectMetricsNet(10, ServiceFabricHelpers.GetEnvironmentProperties(context), true)
				.SendToElasticSearch(esMetricsConfig)
				.Start();

			TraceLogger.BulkMessageInterval = TimeSpan.FromSeconds(10);
			Logger.TelemetryConsumers.Add(new SerilogTelemetryConsumer());
			Logger.TelemetryConsumers.Add(new MetricNetTelemetryConsumer());
		}
        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);
        }
        private static void ConfigureLogging(ContainerBuilder containerBuilder)
        {
            //var endpoint = new Uri(ConfigurationManager.AppSettings.Get("DocumentDbEndpoint"));
            //var seed = ConfigurationManager.AppSettings.Get("DocumentDbSeed");

            //ILogger seriLogger;

            //try
            //{
            //    seriLogger = new LoggerConfiguration()
            //        .WriteTo.AzureDocumentDB(endpoint, seed)
            //        .WriteTo.RollingFile("CheckSwpProject.log")
            //        .CreateLogger();
            //}
            //catch (Exception)
            //{
            //    seriLogger = new LoggerConfiguration()
            //        .WriteTo.RollingFile("CheckSwpProject.log")
            //        .CreateLogger();
            //}

            var seriLogger = new LoggerConfiguration()
                    .WriteTo.RollingFile("CheckSwpProject.log")
                    .CreateLogger();

            var consoleLogger = new ConsoleLogger(seriLogger);

            containerBuilder.RegisterInstance(consoleLogger).As<ILoggerFacade>().SingleInstance();
        }
Exemple #18
0
        void Application_Start(object sender, EventArgs e)
        {
            // Code that runs on application startup
              AreaRegistration.RegisterAllAreas();
              GlobalConfiguration.Configure(WebApiConfig.Register);
              RouteConfig.RegisterRoutes(RouteTable.Routes);

            // Apply the HandleException attribute to all MVC controllers.
            // It extends the MVC HandleError attribute so that it catches HTTP errors with status 500 and displays them nicely
            // instead of defaulting to the IIS error page.
            GlobalFilters.Filters.Add(new CustomHandleError());

            // Apply the CustomAuthorize filter to all MVC controllers.
            // It extends the MVC Authorize attribute to take care of role-checking and making sure user accounts have not been disabled.
            // To prevent a controller from needing authentication and authorization (like AccountController), use [AllowAnonymous].
            // To enforce a role on an MVC controller or action, use [CustomAuthorize(Roles = "admin")].
            GlobalFilters.Filters.Add(new CustomAuthorize());

            // Apply the CustomApiAuthorize filter to all API controllers.
            // It extends the API Authorize attribute to take care of role-checking and making sure user accounts have not been disabled.
            // To enforce a role on an API controller or action, use [CustomApiAuthorize(Roles = "admin")].
            GlobalConfiguration.Configuration.Filters.Add(new CustomApiAuthorize());

            // Apply the ValidateApiModel attribute to all API controllers.
            // It extends the ActionFilterAttribute to perform model validation on DTOs that use the System.DataComponents.DataAnnotations annotations.
            // If the model does not validate, it returns a 400 Bad Request with error messages specified in the annotations.
            GlobalConfiguration.Configuration.Filters.Add(new ValidateApiModelAttribute());

            // Serilog.
            using (var log = new LoggerConfiguration().ReadFrom.AppSettings().CreateLogger())
            {
                log.Information("Application_Start: the SLLInvoices application has started");
            }
        }
Exemple #19
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) }));
    }
Exemple #20
0
        public static void Init()
        {
            var logger = new Serilog.LoggerConfiguration()
                         .MinimumLevel.Debug()
                         .Enrich.FromLogContext()
                         .WriteTo.Async(x => x.File("fork.serilog", fileSizeLimitBytes: 104857600))
                         .CreateLogger();

            AppDomain.CurrentDomain.UnhandledException += (s, e) =>
            {
                logger.Fatal(e.ExceptionObject as Exception, "Unhandled exception");
            };

            var forkConfig = AppConfigParser.Parse();

            bufferSize = forkConfig.DestinationsBufferSize;
            fork       = forkConfig.CreateFork(logger);
            fork.Run();

            instance = new ObservableCollection <ViewEntry>(forkConfig.Destinations.Select(x =>
                                                                                           new ViewEntry
            {
                Address     = x.Id,
                BufferState = string.Empty,
                Kind        = "Destination",
                State       = true
            }).Prepend(new ViewEntry
            {
                Address     = forkConfig.Source.Id,
                BufferState = string.Empty,
                Kind        = "Source",
                State       = true
            }));
        }
Exemple #21
0
        static void Main(string[] args)
        {
            // Assign SwitchableLogger.Instance to Serilog.Log.Logger
            Serilog.Log.Logger = SwitchableLogger.Instance;

            // Assign logger to SwitchableLogger.Instance
            SwitchableLogger.Instance.Logger = new Serilog.LoggerConfiguration()
                                               .MinimumLevel.Verbose()
                                               .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3} {SourceContext}] {Message:lj}{NewLine}{Exception}")
                                               .CreateLogger();

            // Create logger
            ILogger logger = Serilog.Log.ForContext <Program>();

            // Write
            logger.Information("Hello World");

            // Reconfigure
            ILogger newLogger = new Serilog.LoggerConfiguration()
                                .MinimumLevel.Verbose()
                                .WriteTo.Console(outputTemplate: "[{SourceContext}] {Message:lj}{NewLine}{Exception}")
                                .CreateLogger();

            // Assign new logger
            SwitchableLogger.Instance.Set(newLogger, disposePrev: true);

            // Write with the previous logger instance, but with different settings
            logger.Information("Hello world again");
        }
Exemple #22
0
        public void Init()
        {
            var serilogger = new Serilog.LoggerConfiguration().CreateLogger();
            var logger     = new LoggerFactory().AddSerilog(serilogger).CreateLogger <PaperTradeManagerTests>();

            _tradeManager = new PaperTradeManager(new BaseExchange(new ExchangeOptions()), new TheScalper(), null, logger, new TradeOptions(), new InMemoryDataStore());
        }
        public static async Task <int> Main(string[] args)
        {
            /* easy concrete logger that uses a file for demos */
            Serilog.ILogger lgr = new Serilog.LoggerConfiguration()
                                  .WriteTo.Console()
                                  .WriteTo.File("MyCompany.MyExamples.WorkerServiceExampleOne.ConsoleOne.log.txt", rollingInterval: Serilog.RollingInterval.Day)
                                  .CreateLogger();

            try
            {
                /* look at the Project-Properties/Debug(Tab) for this environment variable */
                string environmentName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
                Console.WriteLine(string.Format("ASPNETCORE_ENVIRONMENT='{0}'", environmentName));
                Console.WriteLine(string.Empty);

                Console.WriteLine(string.Format("Environment.UserName='******'", Environment.UserName));
                Console.WriteLine(string.Empty);

                string basePath = Directory.GetCurrentDirectory();
                basePath = GetBasePath();

                Console.WriteLine(string.Format("GetBasePath='{0}'", basePath));
                Console.WriteLine(string.Empty);

                // when using single file exe, the hosts config loader defaults to GetCurrentDirectory
                // which is where the exe is, not where the bundle (with appsettings) has been extracted.
                // when running in debug (from output folder) there is effectively no difference
                string realPath = Directory.GetParent(System.Reflection.Assembly.GetExecutingAssembly().Location).FullName;
                Console.WriteLine(string.Format("realPath='{0}'", realPath));
                Console.WriteLine(string.Empty);

                IConfigurationBuilder builder = new ConfigurationBuilder()
                                                .SetBasePath(realPath)
                                                .AddJsonFile("appsettings.json")
                                                .AddJsonFile($"appsettings.{environmentName}.json", true, true)
                                                .AddEnvironmentVariables();

                IConfigurationRoot configuration = builder.Build();

                using (IHost host = Host.CreateDefaultBuilder(args)
                                    .UseContentRoot(realPath)
                                    .UseSystemd()
                                    .ConfigureServices((_, services) => AppendDi(services, configuration, lgr)).Build())
                {
                    await host.StartAsync();

                    await host.WaitForShutdownAsync();
                }
            }
            catch (Exception ex)
            {
                string flattenMsg = GenerateFullFlatMessage(ex, true);
                Console.WriteLine(flattenMsg);
            }

            Console.WriteLine("Press ENTER to exit");
            Console.ReadLine();

            return(0);
        }
Exemple #24
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);
        }
        public static void Configure()
        {
            var logConfig = new LoggerConfiguration()
                .WriteTo.SignalR(GlobalHost.ConnectionManager.GetHubContext<LoggingHub>());

            Log.Logger = logConfig.CreateLogger();
        }
Exemple #26
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                //app.UseDatabaseErrorPage();
                //app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }
            string webRootPath = env.WebRootPath + "/serugees-api-{Date}.log";
            var    log         = new Serilog.LoggerConfiguration()
                                 .MinimumLevel.Debug()
                                 .WriteTo.RollingFile(
                pathFormat: (webRootPath),
                outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} {SourceContext} [{Level}] {Message}{NewLine}{Exception}")
                                 .CreateLogger();

            loggerFactory.AddSerilog(log);
            app.UseMvc();
        }
Exemple #27
0
        public static LoggerConfiguration ConfigureSerilog(string logDir = null, IConfiguration config = null)
        {
            var libPath = Assembly.GetEntryAssembly().Location;
            var libDir  = Path.GetDirectoryName(libPath);
            var libName = Path.GetFileNameWithoutExtension(libPath);

            if (logDir == null)
            {
                logDir = libDir;
            }
            var logPath = Path.Combine(logDir, $"{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);
            if (config != null)
            {
                loggerConfig.ReadFrom.Configuration(config);
            }

            return(loggerConfig);
        }
Exemple #28
0
        private static void ConfigureSeriLogging(IServiceCollection serviceCollection)
        {
            var connectionString = Configuration.GetConnectionString("NorthWindCon");
            var minLevel         = (LogEventLevel)Enum.Parse(typeof(LogEventLevel), Configuration.GetSection("DBLogLevel").Value);


            var columnOption = new ColumnOptions();

            columnOption.Store.Remove(StandardColumn.MessageTemplate);

            columnOption.AdditionalDataColumns = new Collection <DataColumn>
            {
                new DataColumn {
                    DataType = typeof(string), ColumnName = "OtherData"
                },
                new DataColumn {
                    DataType = typeof(string), ColumnName = "Source"
                },
                new DataColumn {
                    DataType = typeof(string), ColumnName = "Application"
                },
            };
            ILogger logger = new Serilog.LoggerConfiguration()
                             .ReadFrom.Configuration(Configuration)
                             .WriteTo.Logger(lc => lc
                                             .MinimumLevel.Information()
                                             .Filter.ByIncludingOnly(expression: "StartsWith(Source, 'APIClient.Log')")
                                             .WriteTo.MSSqlServer(connectionString, "Logs", restrictedToMinimumLevel: minLevel, columnOptions: columnOption)
                                             )
                             .CreateLogger();

            serviceCollection.AddSingleton <ILogger>(logger);
        }
Exemple #29
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;
        }
Exemple #30
0
 public ILogger GetLogger()
 {
     var loggerConfig = new LoggerConfiguration()
         .WriteTo.ColoredConsole(LogEventLevel.Debug)
         .Enrich.With(new ProcessIdEnricher());
     return loggerConfig.CreateLogger();
 }
Exemple #31
0
        static int Main()
        {
            int? port = null;
            string tag = null;

            var logger = new LoggerConfiguration()
               .UseArtemis()
               .ReadFrom.AppSettings()
               .CreateLogger();
            global::Serilog.Log.Logger = logger;

            return (int)HostFactory.Run(x =>
            {
                x.UseAssemblyInfoForServiceInfo();
                x.UseSerilog(logger);
                x.Service<ArtemisService>(s =>
                {
                    s.ConstructUsing(() => new ArtemisService(port, logger, tag));
                    s.WhenStarted(v => v.Start());
                    s.WhenStopped(v => v.Stop());
                });

                x.SetStartTimeout(TimeSpan.FromSeconds(10));
                x.SetStopTimeout(TimeSpan.FromSeconds(10));

                x.AddCommandLineDefinition("uiport", v => port = int.Parse(v));
                x.AddCommandLineDefinition("tag", v => tag = v);
            });
        }
Exemple #32
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();
 }
        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();
        }
Exemple #34
0
        public Startup(
            IHostingEnvironment hostingEnvironment,
            ILoggerFactory loggerFactory)
        {
            _logger = loggerFactory.CreateLogger<Startup>();

            var configuration = new Configuration();
            configuration.AddJsonFile("config.json");
            configuration.AddEnvironmentVariables();
            var loggingConfiguration = configuration.GetSubKey("Logging");

            var serilog = new LoggerConfiguration()
                .MinimumLevel.Verbose()
                .Enrich.WithMachineName()
                .Enrich.WithProcessId()
                .Enrich.WithThreadId();

            if (string.Equals(hostingEnvironment.EnvironmentName, "Development", StringComparison.OrdinalIgnoreCase))
            {
                serilog.WriteTo.ColoredConsole();
            }

            string elasticSearchConnectionString;
            if (loggingConfiguration.TryGet("ElasticSearch:Server", out elasticSearchConnectionString))
            {
                serilog.WriteTo.ElasticSearch(node: new Uri(elasticSearchConnectionString));
            }

            loggerFactory.AddSerilog(serilog);
        }
Exemple #35
0
        public override void Run()
        {
            var cs = CloudConfigurationManager.GetSetting("StorageConnectionString");

            CloudStorageAccount storageAccount;
            CloudStorageAccount.TryParse(cs, out storageAccount);
            var log = new LoggerConfiguration().WriteTo.AzureTableStorage(storageAccount).CreateLogger();

            log.Information("Who let azure out");

            log.Information("Starting processing of messages");

            // Initiates the message pump and callback is invoked for each message that is received, calling close on the client will stop the pump.
            _client.OnMessage((receivedMessage) =>
                {
                    try
                    {
                        // Process the message
                        Trace.WriteLine("Processing Service Bus message: " + receivedMessage.SequenceNumber.ToString());
                    }
                    catch(Exception e)
                    {
                        // Handle any message processing specific exceptions here
                    }
                });

            _completedEvent.WaitOne();
        }
Exemple #36
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");
        }
        public void SetUp()
        {
            var delegatingSink = new DelegatingSink(evt => { _loggedEvent = evt; });
            var logger = new LoggerConfiguration().MinimumLevel.Verbose().WriteTo.Sink(delegatingSink).CreateLogger();

            _loggedEvent = null;
            _traceListener = new global::SerilogTraceListener.SerilogTraceListener(logger);
        }
Exemple #38
0
 void Application_End(object sender, EventArgs e)
 {
     // Serilog.
     using (var log = new LoggerConfiguration().ReadFrom.AppSettings().CreateLogger())
     {
         log.Information("Application_End: the SLLInvoices application is being shut down");
     }
 }
 public static void Run()
 {
     var logger = new LoggerConfiguration()
     .WriteTo.MSSqlServer(@"Server=.;Database=LogEvents;Trusted_Connection=True;", "Logs")
     .CreateLogger();
     logger.Information("I am an information log");
     logger.Error("Hello, I am an error log");
 }
Exemple #40
0
 protected override LoggerConfiguration ConfigureSerilog(LoggerConfiguration configuration)
 {
     var nodeUris = ConfigurationManager.AppSettings["SerilogNodeUris"];
     var indexFormat = ConfigurationManager.AppSettings["SerilogIndexFormat"];
     return configuration
         .WriteTo.Elasticsearch(nodeUris, indexFormat)
         .WriteTo.ColoredConsole();
 }
        public ILogger ConfigureLogging()
        {
            var logger = new LoggerConfiguration()
                .ReadFrom.AppSettings()
                .CreateLogger();

            Log.Logger = logger;
            return logger;
        }
        public override void Log(ExceptionLoggerContext context)
        {
            using (var log = new LoggerConfiguration().ReadFrom.AppSettings().CreateLogger())
            {
                log.Error(context.Exception, "CustomExceptionLogger: An exception occurred in an API controller; see the log entry below for the request");
            }

            base.Log(context);
        }
Exemple #43
0
        public static ILogger ConfigureLogger()
        {
            var logger = new Serilog.LoggerConfiguration()
                         .ReadFrom.AppSettings()
                         .Enrich.WithProperty("ServiceType", "Hive.Cluster.ServiceDiscovery")
                         .CreateLogger();

            return(logger);
        }
Exemple #44
0
 static void Main(string[] args)
 {
     var log = new LoggerConfiguration()
         .WriteTo.ColoredConsole()
         .CreateLogger();
     SimpleTrace.Diagnostics = log;
     SimpleTrace.Analytics = log;
     Task.Run(() => Main2Async()).Wait();
 }
 public static void ParameterizedLog()
 {
     // Create Logger
     var logger = new LoggerConfiguration()
         .WriteTo.Console()
         .CreateLogger();
     // write structured data
     logger.Information("Processed {Number} records in {Time} ms", 500, 120);
 }
Exemple #46
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
        }
Exemple #47
0
        private void ConfigureLogging(IServiceCollection services)
        {
            var appInsightsConfig = TelemetryConfiguration.CreateDefault();
            var logger            = new Serilog.LoggerConfiguration()
                                    .WriteTo.Console()
                                    .WriteTo.ApplicationInsights(appInsightsConfig, TelemetryConverter.Traces)
                                    .CreateLogger();

            services.AddLogging(lb => lb.AddSerilog(logger));
        }
Exemple #48
0
        static void Main(string[] args)
        {
            // First, configure and start a local silo
            var siloConfig = ClusterConfiguration.LocalhostPrimarySilo();

            siloConfig.Globals.RegisterStorageProvider <MemoryStorage>("OrleansStorage");
            siloConfig.Globals.Application.SetDefaultCollectionAgeLimit(ageLimit: TimeSpan.FromMinutes(1));

            siloConfig.Globals.Application.SetCollectionAgeLimit(type: typeof(LinkStage0Grain), ageLimit: TimeSpan.FromMinutes(1));
            siloConfig.Globals.Application.SetCollectionAgeLimit(type: typeof(LinkStage1Grain), ageLimit: TimeSpan.FromMinutes(2));
            siloConfig.Globals.Application.SetCollectionAgeLimit(type: typeof(LinkStage2Grain), ageLimit: TimeSpan.FromMinutes(3));

            var logger = new Serilog.LoggerConfiguration()
                         .WriteTo.Console()
                         .CreateLogger();
            var serilogConsumer = new SerilogConsumer(logger);

            LogManager.LogConsumers.Add(serilogConsumer);
            //LogManager.TelemetryConsumers.Add(serilogConsumer);

            var silo = new SiloHost("TestSilo", siloConfig);

            silo.InitializeOrleansSilo();
            silo.StartOrleansSilo();

            Console.WriteLine("Silo started.");

            // Then configure and connect a client.
            var clientConfig = ClientConfiguration.LocalhostSilo();
            var client       = new ClientBuilder().UseConfiguration(clientConfig).Build();

            client.Connect().Wait();

            Console.WriteLine("Client connected.");


            ////
            //// This is the place for your test code.
            ////

            //ClientCall(clientConfig, client);


            Console.WriteLine("\nPress Enter to terminate...");
            Console.ReadLine();

            // Shut down
            //client.Close();
            silo.ShutdownOrleansSilo();
        }
        public static void Main(string[] args)
        {
            // Initial configuration
            MemoryConfiguration config = new MemoryConfiguration()
                                         .Set("Serilog:WriteTo:0:Name", "Console")
                                         .Set("Serilog:WriteTo:0:Args:OutputTemplate", "[{Timestamp:HH:mm:ss} {Level:u3} {SourceContext}] {Message:lj}{NewLine}{Exception}")
                                         .Set("Serilog:WriteTo:0:Args:RestrictedToMinimumLevel", "Information");

            // Read configuration
            IConfigurationRoot configuration = new ConfigurationBuilder()
                                               .Add(config)
                                               .Build();

            // Serilog initial configuration
            SwitchableLogger.Instance.Logger = new Serilog.LoggerConfiguration()
                                               .MinimumLevel.Verbose()
                                               .ReadFrom.Configuration(configuration)
                                               .CreateLogger();

            // Service collection
            IServiceCollection serviceCollection = new ServiceCollection()
                                                   .AddLogging(loggingBuilder =>
                                                               loggingBuilder
                                                               .AddSerilog(SwitchableLogger.Instance, true));

            // Services
            using (var services = serviceCollection.BuildServiceProvider())
            {
                // Create logger
                Microsoft.Extensions.Logging.ILogger logger = services.GetService <Microsoft.Extensions.Logging.ILogger <Program> >();

                // Write
                logger.LogInformation("Hello World");

                // Modify config
                config.Set("Serilog:WriteTo:0:Args:OutputTemplate", "[{SourceContext}] {Message:lj}{NewLine}{Exception}");
                configuration.Reload();

                // Serilog initial configuration
                Serilog.ILogger newLogger = new Serilog.LoggerConfiguration()
                                            .MinimumLevel.Verbose()
                                            .ReadFrom.Configuration(configuration)
                                            .CreateLogger();
                // Assign new logger
                SwitchableLogger.Instance.Set(newLogger, true);

                // Write with the previous logger instance, but with different settings
                logger.LogInformation("Hello world again");
            }
        }
Exemple #50
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);
        }
        public static async Task <int> Main(string[] args)
        {
            /*
             *
             * example one
             * MyCompany.MyExamples.SystemCommandLineOne.ConsoleOne.exe mytypeone -a valuea -b valueb -c valuec -d valued -e valuee -f valuef -g valueg -h valueh -i valuei
             *
             * example two
             * MyCompany.MyExamples.SystemCommandLineOne.ConsoleOne.exe showdatetime --includedate false --dateformat "MM/dd/yyyy" --includetime
             */

            /* easy concrete logger that uses a file for demos */
            Serilog.ILogger lgr = new Serilog.LoggerConfiguration()
                                  .WriteTo.File("MyCompany.MyExamples.SystemCommandLineOne.ConsoleOne.log.txt", rollingInterval: Serilog.RollingInterval.Day)
                                  .CreateLogger();

            try
            {
                ShowInputArgs(args);

                /* look at the Project-Properties/Debug(Tab) for this environment variable */
                string environmentName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
                Console.WriteLine(string.Format("ASPNETCORE_ENVIRONMENT='{0}'", environmentName));
                Console.WriteLine(string.Empty);

                IConfigurationBuilder builder = new ConfigurationBuilder()
                                                .SetBasePath(Directory.GetCurrentDirectory())
                                                .AddJsonFile("appsettings.json")
                                                .AddJsonFile($"appsettings.{environmentName}.json", true, true)
                                                .AddEnvironmentVariables();

                IConfigurationRoot configuration = builder.Build();

                IServiceProvider servProv = BuildDi(configuration, lgr);

                await RunRootCommandWithMultiCommandsDemo(servProv, args);
            }
            catch (Exception ex)
            {
                string flattenMsg = GenerateFullFlatMessage(ex, true);
                Console.WriteLine(flattenMsg);
            }

            Console.WriteLine("Press ENTER to exit");
            Console.ReadLine();

            return(0);
        }
Exemple #52
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);
        }
Exemple #53
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();
        }
Exemple #54
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(this.Configuration.GetSection("Logging"));
            loggerFactory.AddDebug(LogLevel.Verbose);

            var log = new Serilog.LoggerConfiguration()
                      .MinimumLevel.Debug()
                      .WriteTo.RollingFile(
                pathFormat: env.MapPath("MvcLibrary-{Date}.log"),
                outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} {SourceContext} [{Level}] {Message}{NewLine}{Exception}")
                      .CreateLogger();

            loggerFactory.AddSerilog(log);

            app.UseMvc();
        }
Exemple #55
0
        /// <summary>Creates a <c>Window</c> object leaving it in <see><c>Starting</c></see> state.</summary>
        /// <remarks>
        ///     Internally, this class contains a <see><c>RenderEngine</c></see> and a <see><c>Loader</c></see>.
        ///     This constructor will create these objects and store them in attributes.
        /// </remarks>
        /// <param name="width">Desired window width.</param>
        /// <param name="height">Desired window height.</param>
        /// <param name="app">Application to be used.</param>
        public Window(int width, int height, IApplication app) :
            base(width, height, GraphicsMode.Default, app.Title)
        {
            State        = WindowStage.Starting;
            _application = app;
            _loader      = Engine.Loader();
            Renderer     = new BasicRenderer();
            RunningTime  = 0.0f;

            var __log = new Serilog.LoggerConfiguration()
                        .WriteTo.File("sharpen.log")
                        .CreateLogger();

            l.Logger = __log;
            l.Information("Created window.");
        }
Exemple #56
0
        /// <summary>
        /// Initializes a new instance of the WebHostBuilder class with pre-configured defaults.
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        public static IWebHostBuilder CreateWebHostBuilder(string[] args)
        {
            return(WebHost.CreateDefaultBuilder(args)
                   .UseCloudFoundryHosting()
                   .ConfigureAppConfiguration((hostingContext, config) => {
                config.Sources.Clear();
                var env = hostingContext.HostingEnvironment;
                config.AddYamlFile("appsettings.yml", optional: true, reloadOnChange: true)
                .AddYamlFile($"appsettings.{env.EnvironmentName}.yml", optional: true, reloadOnChange: true);

                if (env.IsDevelopment())
                {
                    var appAssembly = Assembly.Load(new AssemblyName(env.ApplicationName));
                    if (appAssembly != null)
                    {
                        // JSON format
                        config.AddUserSecrets(appAssembly, optional: true);
                    }
                }

                config.AddEnvironmentVariables();
                //config.AddConfigServer(env);
                //config.AddEnvironmentVariables();
            })
                   .UseStartup <Startup>()
                   .ConfigureLogging((hostingContext, logging) => {
                var loggingOptions = hostingContext.Configuration.GetSection("LoggingOptions").Get <LoggingOptions>();

                var loggerConfiguration = new Serilog.LoggerConfiguration()
                                          .ReadFrom.ConfigurationSection(hostingContext.Configuration.GetSection("LoggingLevels"))
                                          .Enrich.FromLogContext()
                                          .Enrich.WithProperty("ApplicationName", Utility.ApplicationName())
                                          .Enrich.WithMachineName();

                // check to see if deployed to PCF
                var isPcf = Utility.IsPcf();

                if (isPcf)
                {
                    loggerConfiguration.WriteTo.Console(new JsonFormatter(renderMessage: true));
                }
                else
                {
                    loggerConfiguration.WriteTo.ColoredConsole();
                }
            }));
        }
Exemple #57
0
        private static void ConfigureFileLogger(string fileLogLocation, ILoggerFactory loggerFactory)
        {
            string logFileName  = "dotnetsftp_log";
            string logFilesPath = string.IsNullOrWhiteSpace(fileLogLocation) ?
                                  /* true - default log-location to application exe-dir */ Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + @"\Logs"
                :
                                  /* false - use the provided log-location */ fileLogLocation;

            // instantiate and configure logging. Using serilog here, to log to console and a text-file.
            Serilog.ILogger loggerConfig = new Serilog.LoggerConfiguration()
                                           .WriteTo.File($@"{logFilesPath}\{logFileName}.txt", rollingInterval: RollingInterval.Day)
                                           .MinimumLevel.Verbose()
                                           .CreateLogger();
            loggerFactory.AddSerilog(loggerConfig);

            Console.WriteLine($"Logging to '{logFilesPath}\\{logFileName}.txt");
        }
Exemple #58
0
        static SerilogAdapter()
        {
            var logFilePath    = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"my-logs\myapp_.txt");
            var outputTemplate = "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] <ThreadId: {ThreadId}> {Message:lj}{NewLine}{Properties}{NewLine}{Exception}";
            var config         = new Serilog.LoggerConfiguration()
                                 .Enrich.FromLogContext()
                                 .Enrich.WithThreadId()
                                 .Enrich.WithProperty("App", "MacroContext")
                                 .MinimumLevel.Debug()
                                 .WriteTo.File(
                outputTemplate: outputTemplate,
                path: logFilePath,
                rollingInterval: RollingInterval.Day,
                retainedFileCountLimit: 5);

            _loggerConfig = config;
        }
Exemple #59
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;
        }
        public void PublicInterfaceReverseProxyTest()
        {
            Type iLogEventEnricherType = typeof(Serilog.Core.ILogEventEnricher);

            var resetEvent = new ManualResetEventSlim();

            var instance = new PublicLogEventEnricherImpl(resetEvent);

            var proxy = instance.DuckCast(iLogEventEnricherType);
            var log   = new Serilog.LoggerConfiguration()
                        .Enrich.With((Serilog.Core.ILogEventEnricher)proxy)
                        .MinimumLevel.Debug()
                        .WriteTo.Console()
                        .CreateLogger();

            log.Information("Hello world");

            Assert.True(resetEvent.Wait(5_000));
        }