Ejemplo n.º 1
0
        internal static LoggerConfiguration ConfigureLoki(this LoggerConfiguration configuration, LokiOptions lokiOptions, bool dynamicLevel)
        {
            if (lokiOptions is null || lokiOptions.Enabled is false)
            {
                return(configuration);
            }

            if (string.IsNullOrEmpty(lokiOptions.Endpoint))
            {
                throw new TitanException("Loki cannot be null or empty.");
            }


            LokiCredentials credentials;

            if (lokiOptions.Credentials is null)
            {
                credentials = new NoAuthCredentials(lokiOptions.Endpoint);
            }
            else
            {
                credentials = new BasicAuthCredentials(lokiOptions.Endpoint, lokiOptions.Credentials.Username, lokiOptions.Credentials.Password);
            }

            configuration.WriteTo.TitanLoki(credentials, null, null, TitanLibHelper.GetLogLevel(lokiOptions.LogLevelRestriction),
                                            lokiOptions.BatchSizeLimit, lokiOptions.Period.ToTimeSpan(), lokiOptions.QueueLimit, dynamicLevel);
            return(configuration);
        }
Ejemplo n.º 2
0
        public static int Main(string[] args)
        {
            var credentials = new NoAuthCredentials("http://loki:3100");

            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Debug()
                         .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
                         .Enrich.FromLogContext()
                         .WriteTo.Console()
                         .WriteTo.LokiHttp(credentials, new LogLabelProvider("aspnetcore-demo-app"))
                         .CreateLogger();

            try
            {
                Log.Information("Starting web host");
                CreateHostBuilder(args).Build().Run();
                return(0);
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "Host terminated unexpectedly");
                return(1);
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }
Ejemplo n.º 3
0
        private static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
        .ConfigureHostConfiguration(configurationBuilder => {
            configurationBuilder.AddCommandLine(args);
        })
        .ConfigureAppConfiguration((ctx, builder) =>
        {
            builder.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .AddJsonFile($"appsettings.{ctx.HostingEnvironment.EnvironmentName}.json", optional: true, reloadOnChange: true)
            .AddEnvironmentVariables();
        })
        .UseSerilog((ctx, cfg) =>
        {
            var credentials = new NoAuthCredentials(ctx.Configuration.GetConnectionString("loki"));

            cfg.MinimumLevel.Verbose()
            .Enrich.FromLogContext()
            .Enrich.WithProperty("Application", ctx.HostingEnvironment.ApplicationName)
            .Enrich.WithProperty("Environment", ctx.HostingEnvironment.EnvironmentName)
            .WriteTo.Console(new RenderedCompactJsonFormatter())
            .WriteTo.LokiHttp(credentials);
        })
        .ConfigureServices((hostContext, services) =>
        {
            services.AddSingleton <IEventDeserializer>(new JsonEventDeserializer(new[]
            {
                typeof(CustomerCreated).Assembly
            }));

            services.AddHttpClient <ICustomersApiClient, CustomersApiClient>("customersApiClient", (ctx, httpClient) =>
            {
                var config             = ctx.GetRequiredService <IConfiguration>();
                var endpoint           = config["CustomersApi"];
                httpClient.BaseAddress = new System.Uri(endpoint);
            })
            .AddPolicyHandler(HttpClientPolicies.GetRetryPolicy());

            services.AddSingleton <INotificationsFactory, NotificationsFactory>();
            services.AddSingleton <INotificationsService, FakeNotificationsService>();

            services.AddSingleton(ctx =>
            {
                var kafkaConnStr    = hostContext.Configuration.GetConnectionString("kafka");
                var eventsTopicName = hostContext.Configuration["eventsTopicName"];
                var groupName       = hostContext.Configuration["eventsTopicGroupName"];
                return(new EventConsumerConfig(kafkaConnStr, eventsTopicName, groupName));
            });

            services.AddHostedService(ctx =>
            {
                var logger               = ctx.GetRequiredService <ILogger <EventConsumer <Account, Guid> > >();
                var eventsDeserializer   = ctx.GetRequiredService <IEventDeserializer>();
                var consumerConfig       = ctx.GetRequiredService <EventConsumerConfig>();
                var notificationsFactory = ctx.GetRequiredService <INotificationsFactory>();
                var notificationsService = ctx.GetRequiredService <INotificationsService>();
                var consumer             = new EventConsumer <Account, Guid>(eventsDeserializer, consumerConfig, logger);

                return(new AccountEventsWorker(notificationsFactory, notificationsService, consumer, logger));
            });
        });
Ejemplo n.º 4
0
        public static void Main(string[] args)
        {
            #region Send Logs to Loki using Serilog

            /*
             *  Required NuGet Packages
             *
             *  - Serilog.AspNetCore
             *  - Serilog.Sinks.Loki
             */

            var lokiCredentials = new NoAuthCredentials("http://localhost:3100");

            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Warning()
                         .Enrich.FromLogContext()
                         .WriteTo.LokiHttp(lokiCredentials, new LogLabelProvider())
                         .CreateLogger();

            #endregion

            try
            {
                Log.Information("Starting up");
                CreateHostBuilder(args).Build().Run();
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "Application start-up failed");
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }
Ejemplo n.º 5
0
        public static IHostBuilder UseLogging(this IHostBuilder hostBuilder, string applicationName = "")
        {
            hostBuilder.UseSerilog((context, loggerConfiguration) =>
            {
                var appOptions     = context.Configuration.GetOptions <AppOptions>("App");
                var loggingOptions = context.Configuration.GetOptions <LoggingOptions>("Logging");

                applicationName = string.IsNullOrWhiteSpace(applicationName) ? appOptions.Name : applicationName;

                loggerConfiguration
                .ReadFrom.Configuration(context.Configuration, "Logging")
                .Enrich.FromLogContext()
                .Enrich.WithProperty("Environment", context.HostingEnvironment.EnvironmentName)
                .Enrich.WithProperty("ApplicationName", applicationName);

                if (loggingOptions.ConsoleEnabled)
                {
                    loggerConfiguration.WriteTo
                    .Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3} {Properties:j}] {Message:lj}{NewLine}{Exception}");
                }
                if (loggingOptions.Seq.Enabled)
                {
                    loggerConfiguration.WriteTo.Seq(loggingOptions.Seq.Url, apiKey: loggingOptions.Seq.ApiKey);
                }
                if (loggingOptions.Loki != null && loggingOptions.Loki.Enabled)
                {
                    var credentials = new NoAuthCredentials(loggingOptions.Loki.Url);
                    loggerConfiguration.WriteTo.LokiHttp(credentials, new LokiLogLabelProvider(context.HostingEnvironment.EnvironmentName, applicationName));
                }
            });

            return(hostBuilder);
        }
Ejemplo n.º 6
0
        public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration((ctx, builder) =>
        {
            builder.AddJsonFile("appsettings.json", optional: false);

#if OnPremise
            builder.AddJsonFile($"appsettings.OnPremise-{ctx.HostingEnvironment.EnvironmentName}.json", optional: true);
#endif

#if OnAzure
            builder.AddJsonFile($"appsettings.OnAzure-{ctx.HostingEnvironment.EnvironmentName}.json", optional: true);
#endif

            builder.AddEnvironmentVariables()
            .AddUserSecrets <Startup>();
        })
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup <Startup>();
        }).UseSerilog((ctx, cfg) =>
        {
            var credentials = new NoAuthCredentials(ctx.Configuration.GetConnectionString("loki"));

            cfg.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
            .Enrich.FromLogContext()
            .Enrich.WithProperty("Application", ctx.HostingEnvironment.ApplicationName)
            .Enrich.WithProperty("Environment", ctx.HostingEnvironment.EnvironmentName)
            .WriteTo.Console(new RenderedCompactJsonFormatter())
            .WriteTo.LokiHttp(credentials);
        });
Ejemplo n.º 7
0
        private static void SetupLoki(LoggerConfiguration log, IConfiguration cfg)
        {
            var dat = cfg.GetSection("Serilog:Loki").Get <LokiConfigurationData>();

            if (dat == null)
            {
                return;
            }

            LokiCredentials credentials;

            if (string.IsNullOrWhiteSpace(dat.Username))
            {
                credentials = new NoAuthCredentials(dat.Address);
            }
            else
            {
                if (string.IsNullOrWhiteSpace(dat.Password))
                {
                    throw new InvalidDataException("No password specified.");
                }

                credentials = new BasicAuthCredentials(dat.Address, dat.Username, dat.Password);
            }

            log.WriteTo.LokiHttp(credentials, new DefaultLogLabelProvider(new[]
            {
                new LokiLabel("App", "SS14.Changelog"),
                new LokiLabel("Server", dat.Name)
            }));
        }
Ejemplo n.º 8
0
        private void PostLoggingEvent(LoggingEvent[] loggingEvents)
        {
            var formatter  = new LokiBatchFormatter(labels);
            var httpClient = new LokiHttpClient(TrustSelfCignedCerts);

            if (httpClient is LokiHttpClient c)
            {
                LokiCredentials credentials;

                if (!string.IsNullOrEmpty(BasicAuthUserName) && !string.IsNullOrEmpty(BasicAuthPassword))
                {
                    credentials = new BasicAuthCredentials(ServiceUrl, BasicAuthUserName, BasicAuthPassword);
                }
                else
                {
                    credentials = new NoAuthCredentials(ServiceUrl);
                }

                c.SetAuthCredentials(credentials);
            }

            using (MemoryStream ms = new MemoryStream())
                using (var sc = new StreamWriter(ms))
                {
                    formatter.Format(loggingEvents, sc);
                    sc.Flush();
                    ms.Position = 0;
                    var content    = new StreamContent(ms);
                    var contentStr = content.ReadAsStringAsync().Result; // TO VERIFY
                    httpClient.PostAsync(LokiRouteBuilder.BuildPostUri(ServiceUrl), content);
                }
        }
Ejemplo n.º 9
0
        private bool SetupLoki()
        {
            _config.RegisterCVar("loki.enabled", false);
            _config.RegisterCVar("loki.name", "");
            _config.RegisterCVar("loki.address", "");
            _config.RegisterCVar("loki.username", "");
            _config.RegisterCVar("loki.password", "");

            var enabled = _config.GetCVar <bool>("loki.enabled");

            if (!enabled)
            {
                return(true);
            }

            var serverName = _config.GetCVar <string>("loki.name");
            var address    = _config.GetCVar <string>("loki.address");
            var username   = _config.GetCVar <string>("loki.username");
            var password   = _config.GetCVar <string>("loki.password");

            if (string.IsNullOrWhiteSpace(serverName))
            {
                Logger.FatalS("loki", "Misconfiguration: Server name is not specified/empty.");
                return(false);
            }

            if (string.IsNullOrWhiteSpace(address))
            {
                Logger.FatalS("loki", "Misconfiguration: Loki address is not specified/empty.");
                return(false);
            }

            LokiCredentials credentials;

            if (string.IsNullOrWhiteSpace(username))
            {
                credentials = new NoAuthCredentials(address);
            }
            else
            {
                if (string.IsNullOrWhiteSpace(password))
                {
                    Logger.FatalS("loki", "Misconfiguration: Loki password is not specified/empty but username is.");
                    return(false);
                }

                credentials = new BasicAuthCredentials(address, username, password);
            }

            Logger.DebugS("loki", "Loki enabled for server {ServerName} loki address {LokiAddress}.", serverName,
                          address);

            var handler = new LokiLogHandler(serverName, credentials);

            _log.RootSawmill.AddHandler(handler);
            return(true);
        }
Ejemplo n.º 10
0
        public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(webBuilder =>
        {
            /*var promOptions = new PrometheusExporterOptions() { Url = "http://0.0.0.0:15003/metrics/" };
             *  var metric = new Metric<long>("sample");
             *  var promExporter = new PrometheusExporter<long>(promOptions, metric);
             *
             *  try
             *  {
             *      promExporter.Start();
             *      Log.Logger.Information("Now listening on: http://0.0.0.0:15003");
             *
             *      var label1 = new List<KeyValuePair<string, string>>();
             *      label1.Add(new KeyValuePair<string, string>("status_code", "200"));
             *      var labelSet1 = new LabelSet(label1);
             *      metric.GetOrCreateMetricTimeSeries(labelSet1).Add(100);
             *  }
             *  catch
             *  {
             *      //promExporter.Stop();
             *  }*/

            webBuilder.ConfigureKestrel((ctx, options) =>
            {
                options.Limits.MinRequestBodyDataRate = null;
                options.Listen(IPAddress.Any, 15003, options => { });
                options.Listen(IPAddress.Any, 5003, listenOptions =>
                {
                    listenOptions.Protocols = HttpProtocols.Http2;
                });
            });

            webBuilder.UseStartup <Startup>();
        })
        .ConfigureLogging((hostingContext, logging) =>
        {
            var seqUrl = hostingContext.Configuration.GetValue <string>("Seq:Connection");

            var lokiCredentials = new NoAuthCredentials(hostingContext.Configuration.GetValue <string>("Loki:Connection"));

            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Debug()
                         .Enrich.WithProperty("env", hostingContext.HostingEnvironment.EnvironmentName)
                         .Enrich.WithProperty("app", "meteorite-service")
                         .Enrich.FromLogContext()
                         .WriteTo.Console(Serilog.Events.LogEventLevel.Information, "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] [{CorrelationID}] {Message}{NewLine}{Exception}")
                         .WriteTo.Seq(seqUrl)
                         .WriteTo.LokiHttp(lokiCredentials, new LokiLogLabelProvider("meteorite-service", hostingContext.HostingEnvironment.EnvironmentName))
                         .CreateLogger();

            logging.AddSerilog(dispose: true);
        });
Ejemplo n.º 11
0
        public static void ConfigureLogging(string environment, IConfigurationRoot configuration)
        {
            var lokiCredentials = new NoAuthCredentials(configuration.GetSection("Logging").GetSection("Loki")["Uri"]);

            Log.Logger = new LoggerConfiguration()
                         .Enrich.FromLogContext()
                         .Enrich.WithMachineName()
                         .WriteTo.Debug()
                         .WriteTo.Console()
                         .WriteTo.LokiHttp(lokiCredentials)
                         .Enrich.WithProperty("Environment", environment)
                         .ReadFrom.Configuration(configuration)
                         .CreateLogger();
        }
Ejemplo n.º 12
0
        static void Main(string[] args)
        {
            NoAuthCredentials credentials = new NoAuthCredentials("http://*****:*****@Position} in {Elapsed:000} ms.", position, 34);

            using (LogContext.PushProperty("A", 1))
            {
                log.Warning("Warning with Property A");
                log.Fatal("Fatal with Property A");
            }

            using (LogContext.PushProperty("MyAppendPropertyName", 1))
            {
                log.Warning("Warning with Property MyAppendPropertyName");
                log.Fatal("Fatal with Property MyAppendPropertyName");
            }

            log.Dispose();
        }
Ejemplo n.º 13
0
        public void NoAuthHeaderIsCorrect()
        {
            // Arrange
            var credentials = new NoAuthCredentials("http://test:80");
            var log         = new LoggerConfiguration()
                              .MinimumLevel.Information()
                              .WriteTo.LokiHttp(credentials, httpClient: _client)
                              .CreateLogger();

            // Act
            log.Error("Something's wrong");
            log.Dispose();

            // Assert
            _client.Client.DefaultRequestHeaders.Authorization.ShouldBeNull();
        }
Ejemplo n.º 14
0
        public void RequestUriIsCorrect(string address)
        {
            // Arrange
            var credentials = new NoAuthCredentials(address);
            var log         = new LoggerConfiguration()
                              .MinimumLevel.Information()
                              .WriteTo.LokiHttp(credentials, httpClient: _client)
                              .CreateLogger();

            // Act
            log.Error("Something's wrong");
            log.Dispose();

            // Assert
            _client.RequestUri.ShouldBe(LokiRouteBuilder.BuildPostUri(credentials.Url));
        }
Ejemplo n.º 15
0
        public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup <Startup>();
        }).UseSerilog((ctx, cfg) =>
        {
            var credentials = new NoAuthCredentials(ctx.Configuration.GetConnectionString("loki"));

            cfg.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
            .Enrich.FromLogContext()
            .Enrich.WithProperty("Application", ctx.HostingEnvironment.ApplicationName)
            .Enrich.WithProperty("Environment", ctx.HostingEnvironment.EnvironmentName)
            .WriteTo.Console(new RenderedCompactJsonFormatter())
            .WriteTo.LokiHttp(credentials);
        });
Ejemplo n.º 16
0
        public void ContentMatchesApproved()
        {
            // Arrange
            var credentials = new NoAuthCredentials("http://*****:*****@"\d{1,2}\d{1,2}\d{2,4}-\d{1,2}-\d{1,2}T\d{1,2}:\d{1,2}:\d{1,2}.\d{1,7}\+\d{2}:\d{2}", "<datetime>")));
        }
Ejemplo n.º 17
0
        public static void Main(string[] args)
        {
            //var configuration = new ConfigurationBuilder()
            //    .AddJsonFile("appsettings.json")
            //    .Build();


            var credentials = new NoAuthCredentials("http://localhost:3100"); // Address to local or remote Loki server

            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Information()
                         .Enrich.FromLogContext()
                         .WriteTo.LokiHttp(credentials)
                         .WriteTo.Console()
                         .CreateLogger();

            CreateHostBuilder(args).Build().Run();
        }
Ejemplo n.º 18
0
        public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(webBuilder => {
            webBuilder.UseStartup <Startup>();
        }).UseSerilog((context, config) => {
            var credentials = new NoAuthCredentials(Environment.GetEnvironmentVariable("LOKI_HOST"));

            config
            .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
            .MinimumLevel.Override("System", LogEventLevel.Warning)
            .Enrich.FromLogContext()
            .Enrich.WithProperty("ServerName", Environment.MachineName)
            .Enrich.WithProperty("Application", context.HostingEnvironment.ApplicationName)
            .Enrich.WithProperty("Environment", context.HostingEnvironment.EnvironmentName)
            //.WriteTo.Console(new RenderedCompactJsonFormatter())
            .WriteTo.Console()
            .WriteTo.LokiHttp(credentials);
        });
Ejemplo n.º 19
0
        protected override LoggerConfiguration ConfigureProd(LoggerConfiguration loggerConfiguration,
                                                             string appName)
        {
            LokiCredentials credentials;

            if (!string.IsNullOrEmpty(Config.Login))
            {
                credentials = new BasicAuthCredentials(Config.Url, Config.Login, Config.Password);
            }
            else
            {
                credentials = new NoAuthCredentials(Config.Url);
            }

            loggerConfiguration =
                loggerConfiguration.WriteTo.LokiHttp(credentials, new LogLabelProvider(appName));
            return(loggerConfiguration);
        }
Ejemplo n.º 20
0
        public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup <Startup>();
        }).UseSerilog((ctx, cfg) =>
        {
            var credentials = new NoAuthCredentials("http://localhost:3100");

            cfg.MinimumLevel.Override("Microsoft", LogEventLevel.Warning);        //Microsoft框架本身的日志,仅输出Warning以上级别
            cfg.Enrich.FromLogContext()
            .Enrich.WithProperty("App", ctx.HostingEnvironment.ApplicationName)
            .Enrich.WithProperty("ENV", ctx.HostingEnvironment.EnvironmentName)
            .WriteTo.LokiHttp(credentials)
            .WriteTo.Console();

            //if (ctx.HostingEnvironment.IsDevelopment())
            //    cfg.WriteTo.Console(new RenderedCompactJsonFormatter());
        });
Ejemplo n.º 21
0
        static void Main(string[] args)
        {
            var r = new DefaultBatchFormatter();

            Exception ex;

            try
            {
                throw new Exception("Something went wrong, see StackTrace for more info");
            }
            catch (Exception e)
            {
                ex = e;
            }

            var credentials = new NoAuthCredentials("http://*****:*****@Position} in {Elapsed:000} ms.", position, elapsedMs);
            }

/*            log.Information("1# Logging {@Heartbeat:l} from {Computer:l}", "SomeValue", "SomeOtherValue");*/

/*            var position = new { Latitude = 25, Longitude = 134 };
 *          var exception = new {Message = ex.Message, StackTrace = ex.StackTrace};
 *          var elapsedMs = 34;*/

/*            log.Debug(@"Does this \""break\"" something?");
 *          log.Error("#2 {@Message}", exception);
 *          log.Information("3# Random message processed {@Position} in {Elapsed:000} ms.", position, elapsedMs);*/

            log.Dispose();
        }
        public static void Main(string[] args)
        {
            var credentials = new NoAuthCredentials("http://*****:*****@God}", "asd");
            Log.Warning("The god of the day is {@God}", "asd");
            Log.Error("The god of the day is {@God}", "asd");

            var position  = new { Latitude = 25, Longitude = 134 };
            var elapsedMs = 34;
            Log.Information("Message processed {@Position} in {Elapsed:000} ms.", position, elapsedMs);

            try
            {
                Log.Information("Starting up");
                CreateHostBuilder(args).Build().Run();
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "Application start-up failed");
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }
Ejemplo n.º 23
0
        public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup <Startup>();
        })
        .ConfigureLogging((hostingContext, logging) =>
        {
            var seqUrl = hostingContext.Configuration.GetValue <string>("Seq:Connection");

            var lokiCredentials = new NoAuthCredentials(hostingContext.Configuration.GetValue <string>("Loki:Connection"));

            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Debug()
                         .Enrich.WithProperty("env", hostingContext.HostingEnvironment.EnvironmentName)
                         .Enrich.WithProperty("app", "product-service")
                         .Enrich.FromLogContext()
                         .WriteTo.Console(Serilog.Events.LogEventLevel.Information, "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] [{CorrelationID}] {Message}{NewLine}{Exception}")
                         .WriteTo.Seq(seqUrl)
                         .WriteTo.LokiHttp(lokiCredentials, new LokiLogLabelProvider("product-service", hostingContext.HostingEnvironment.EnvironmentName))
                         .CreateLogger();

            logging.AddSerilog(dispose: true);
        });
Ejemplo n.º 24
0
        public static void Main(string[] args)
        {
            var lokiCredentials = new NoAuthCredentials("http://localhost:3100");

            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Warning()
                         .Enrich.FromLogContext()
                         .WriteTo.LokiHttp(lokiCredentials, new LogLabelProvider())
                         .CreateLogger();

            try
            {
                Log.Information("Starting up");
                CreateHostBuilder(args).Build().Run();
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "Application start-up failed");
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }
Ejemplo n.º 25
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <ApplicationDbContext>(options =>
                                                         options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            //services.AddDbContext<EquinoxContext>(options =>
            //    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            //services.AddDbContext<EventStoreSQLContext>(options =>
            //    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            services.AddIdentity <ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddDefaultTokenProviders();

            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(o =>
            {
                o.LoginPath        = new PathString("/login");
                o.AccessDeniedPath = new PathString("/home/access-denied");
            })
            .AddFacebook(o =>
            {
                o.AppId     = Configuration["Authentication:Facebook:AppId"];
                o.AppSecret = Configuration["Authentication:Facebook:AppSecret"];
            })
            .AddGoogle(googleOptions =>
            {
                googleOptions.ClientId     = Configuration["Authentication:Google:ClientId"];
                googleOptions.ClientSecret = Configuration["Authentication:Google:ClientSecret"];
            });

            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            var credentials = new NoAuthCredentials("http://localhost:3100");

            LoggerConfiguration loggerConfiguration = new LoggerConfiguration()
                                                      .ReadFrom.Configuration(Configuration)
                                                      .WriteTo.LokiHttp(credentials, new LogLabelProvider())
            ;

            services.AddSerilogServices(loggerConfiguration);

            services.AddAutoMapperSetup();
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            services.AddAuthorization(options =>
            {
                options.AddPolicy("CanWriteCustomerData", policy => policy.Requirements.Add(new ClaimRequirement("Customers", "Write")));
                options.AddPolicy("CanRemoveCustomerData", policy => policy.Requirements.Add(new ClaimRequirement("Customers", "Remove")));
            });

            // Adding MediatR for Domain Events and Notifications
            services.AddMediatR(typeof(Startup));

            // .NET Native DI Abstraction
            RegisterServices(services);
        }
Ejemplo n.º 26
0
        static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)

        .ConfigureServices((hostContext, services) =>
        {
            services.AddLogging(logging => {
                var credentials = new NoAuthCredentials(hostContext.Configuration["Loki"]);

                var logger = new LoggerConfiguration()
                             .MinimumLevel.Debug()
                             .Enrich.WithMachineName()
                             .Enrich.WithEnvironmentUserName()
                             .WriteTo.LokiHttp(credentials)
                             .WriteTo.Console(new RenderedCompactJsonFormatter())
                             .CreateLogger();
                logging.AddSerilog(logger);
            });

            var encoder = new JsonEncoder();
            services.AddSingleton <IEncoder>(encoder);
            services.AddSingleton <IDecoder>(encoder);

            services.AddSingleton <IConnectionFactory>(ctx =>
            {
                var config            = ctx.GetRequiredService <IConfiguration>();
                var rabbitConfig      = config.GetSection("RabbitMQ");
                var connectionFactory = new ConnectionFactory()
                {
                    HostName = rabbitConfig["HostName"],
                    UserName = rabbitConfig["UserName"],
                    Password = rabbitConfig["Password"],
                    Port     = AmqpTcpEndpoint.UseDefaultPort,
                    DispatchConsumersAsync = true
                };
                return(connectionFactory);
            });

            services.AddSingleton <IBusConnection, RabbitPersistentConnection>();
            services.AddSingleton <ICommandResolver>(ctx =>
            {
                var decoder    = ctx.GetRequiredService <IDecoder>();
                var assemblies = new[]
                {
                    typeof(ProcessIncoming).Assembly
                };
                return(new CommandResolver(decoder, assemblies));
            });

            services.AddSingleton <ISubscriber>(ctx =>
            {
                var connection   = ctx.GetRequiredService <IBusConnection>();
                var decoder      = ctx.GetRequiredService <IDecoder>();
                var config       = ctx.GetRequiredService <IConfiguration>();
                var logger       = ctx.GetRequiredService <ILogger <RabbitSubscriber> >();
                var rabbitConfig = config.GetSection("RabbitMQ");

                var exchangeName       = rabbitConfig["Exchange"];
                var queueName          = rabbitConfig["Queue"];
                var deadLetterExchange = rabbitConfig["DeadLetterExchange"];
                var deadLetterQueue    = rabbitConfig["DeadLetterQueue"];
                var options            = new RabbitSubscriberOptions(exchangeName, queueName, deadLetterExchange, deadLetterQueue);

                return(new RabbitSubscriber(connection, options, decoder, logger));
            });

            services.AddSingleton(ctx =>
            {
                var config = ctx.GetRequiredService <IConfiguration>();

                var mongoCfg = config.GetSection("Mongo");
                var connStr  = mongoCfg["ConnectionString"];
                return(new MongoClient(connectionString: connStr));
            })
            .AddSingleton(ctx =>
            {
                var config = ctx.GetRequiredService <IConfiguration>();

                var mongoCfg = config.GetSection("Mongo");
                var dbName   = mongoCfg["DbName"];
                var client   = ctx.GetRequiredService <MongoClient>();
                var database = client.GetDatabase(dbName);
                return(database);
            }).AddSingleton <IDbContext, DbContext>();

            services.AddMediatR(new[] {
                typeof(ProcessIncoming),
                typeof(ProcessIncomingHandler)
            });

            services.AddHostedService <MessagesBackgroundService>();
        });