Ejemplo n.º 1
0
        public static IHostBuilder CreateHostBuilder(IConfiguration config, string environment)
        {
            Console.Title = "Exceptionless Web";

            var options = AppOptions.ReadFromConfiguration(config);

            var loggerConfig = new LoggerConfiguration().ReadFrom.Configuration(config);

            if (!String.IsNullOrEmpty(options.ExceptionlessApiKey))
            {
                loggerConfig.WriteTo.Sink(new ExceptionlessSink(), LogEventLevel.Verbose);
            }

            Log.Logger = loggerConfig.CreateLogger();
            var configDictionary = config.ToDictionary("Serilog");

            Log.Information("Bootstrapping Exceptionless Web in {AppMode} mode ({InformationalVersion}) on {MachineName} with settings {@Settings}", environment, options.InformationalVersion, Environment.MachineName, configDictionary);

            bool useApplicationInsights = !String.IsNullOrEmpty(options.ApplicationInsightsKey);
            var  builder = Host.CreateDefaultBuilder()
                           .UseEnvironment(environment)
                           .ConfigureWebHostDefaults(webBuilder => {
                webBuilder
                .UseConfiguration(config)
                .ConfigureKestrel(c => {
                    c.AddServerHeader = false;
                    // c.AllowSynchronousIO = false; // TODO: Investigate issue with JSON Serialization.

                    if (options.MaximumEventPostSize > 0)
                    {
                        c.Limits.MaxRequestBodySize = options.MaximumEventPostSize;
                    }
                })
                .UseStartup <Startup>();

                if (String.IsNullOrEmpty(webBuilder.GetSetting(WebHostDefaults.ContentRootKey)))
                {
                    webBuilder.UseContentRoot(Directory.GetCurrentDirectory());
                }

                var metricOptions = MetricOptions.ReadFromConfiguration(config);
                if (!String.IsNullOrEmpty(metricOptions.Provider))
                {
                    ConfigureMetricsReporting(webBuilder, metricOptions);
                }
            })
                           .UseSerilog()
                           .ConfigureServices((ctx, services) => {
                services.AddSingleton(config);
                services.AddHttpContextAccessor();

                if (useApplicationInsights)
                {
                    services.AddSingleton <ITelemetryInitializer, ExceptionlessTelemetryInitializer>();
                    services.AddApplicationInsightsTelemetry(options.ApplicationInsightsKey);
                }
            });

            return(builder);
        }
Ejemplo n.º 2
0
    public static IHostBuilder CreateHostBuilder(IConfigurationRoot config, string environment)
    {
        Console.Title = "Exceptionless Web";

        var options = AppOptions.ReadFromConfiguration(config);

        var loggerConfig = new LoggerConfiguration().ReadFrom.Configuration(config)
                           .Enrich.FromLogContext()
                           .Enrich.WithMachineName()
                           .Enrich.WithSpan();

        if (!String.IsNullOrEmpty(options.ExceptionlessApiKey))
        {
            loggerConfig.WriteTo.Sink(new ExceptionlessSink(), LogEventLevel.Information);
        }

        Log.Logger = loggerConfig.CreateBootstrapLogger();
        var configDictionary = config.ToDictionary("Serilog");

        Log.Information("Bootstrapping Exceptionless Web in {AppMode} mode ({InformationalVersion}) on {MachineName} with settings {@Settings}", environment, options.InformationalVersion, Environment.MachineName, configDictionary);

        var builder = Host.CreateDefaultBuilder()
                      .UseEnvironment(environment)
                      .UseSerilog()
                      .ConfigureWebHostDefaults(webBuilder => {
            webBuilder
            .UseConfiguration(config)
            .ConfigureKestrel(c => {
                c.AddServerHeader = false;

                if (options.MaximumEventPostSize > 0)
                {
                    c.Limits.MaxRequestBodySize = options.MaximumEventPostSize;
                }
            })
            .UseStartup <Startup>();
        })
                      .ConfigureServices((ctx, services) => {
            services.AddSingleton(config);
            services.AddAppOptions(options);
            services.AddHttpContextAccessor();
            services.AddApm(new ApmConfig(config, "Exceptionless.Web", "Exceptionless", options.InformationalVersion, options.CacheOptions.Provider == "redis"));
        });

        if (!String.IsNullOrEmpty(options.MetricOptions.Provider))
        {
            ConfigureMetricsReporting(builder, options.MetricOptions);
        }

        return(builder);
    }
Ejemplo n.º 3
0
        public TestWithServices(ServicesFixture fixture, ITestOutputHelper output) : base(output)
        {
            _fixture         = fixture;
            Log.MinimumLevel = LogLevel.Information;
            Log.SetLogLevel <ScheduledTimer>(LogLevel.Warning);

            var appOptions = AppOptions.ReadFromConfiguration(fixture.Configuration);

            _fixture.AddServicesConfiguration(s => {
                s.AddSingleton <ILoggerFactory>(Log);
                s.AddSingleton(typeof(ILogger <>), typeof(Logger <>));
                s.AddAppOptions(appOptions);
                Web.Bootstrapper.RegisterServices(s, appOptions, Log);
                s.AddSingleton <IMailer, NullMailer>();
                s.AddSingleton <IDomainLoginProvider, TestDomainLoginProvider>();
            });
        }
Ejemplo n.º 4
0
    private IServiceProvider CreateContainer()
    {
        var services = new ServiceCollection();

        var config = new ConfigurationBuilder()
                     .SetBasePath(AppContext.BaseDirectory)
                     .AddYamlFile("appsettings.yml", optional: false, reloadOnChange: false)
                     .AddEnvironmentVariables()
                     .Build();

        services.AddSingleton <IConfiguration>(config);
        var appOptions = AppOptions.ReadFromConfiguration(config);

        services.AddSingleton(appOptions);
        RegisterServices(services, appOptions);

        return(services.BuildServiceProvider());
    }
Ejemplo n.º 5
0
        public static IHostBuilder CreateHostBuilder(string[] args)
        {
            var jobOptions = new JobRunnerOptions(args);

            Console.Title = jobOptions.JobName != null ? $"Exceptionless {jobOptions.JobName} Job" : "Exceptionless Jobs";

            string environment = Environment.GetEnvironmentVariable("EX_AppMode");

            if (String.IsNullOrWhiteSpace(environment))
            {
                environment = "Production";
            }

            var config = new ConfigurationBuilder()
                         .SetBasePath(Directory.GetCurrentDirectory())
                         .AddYamlFile("appsettings.yml", optional: true, reloadOnChange: true)
                         .AddYamlFile($"appsettings.{environment}.yml", optional: true, reloadOnChange: true)
                         .AddEnvironmentVariables("EX_")
                         .AddEnvironmentVariables("ASPNETCORE_")
                         .AddCommandLine(args)
                         .Build();

            var options = AppOptions.ReadFromConfiguration(config);

            var loggerConfig = new LoggerConfiguration().ReadFrom.Configuration(config);

            if (!String.IsNullOrEmpty(options.ExceptionlessApiKey))
            {
                loggerConfig.WriteTo.Sink(new ExceptionlessSink(), LogEventLevel.Verbose);
            }

            Log.Logger = loggerConfig.CreateLogger();
            var configDictionary = config.ToDictionary("Serilog");

            Log.Information("Bootstrapping Exceptionless {JobName} job(s) in {AppMode} mode ({InformationalVersion}) on {MachineName} with settings {@Settings}", jobOptions.JobName ?? "All", environment, options.InformationalVersion, Environment.MachineName, configDictionary);

            bool useApplicationInsights = !String.IsNullOrEmpty(options.ApplicationInsightsKey);

            var builder = Host.CreateDefaultBuilder()
                          .UseEnvironment(environment)
                          .UseSerilog()
                          .ConfigureWebHostDefaults(webBuilder => {
                webBuilder
                .UseConfiguration(config)
                .Configure(app => {
                    app.UseSerilogRequestLogging(o => o.GetLevel = (context, duration, ex) => {
                        if (ex != null || context.Response.StatusCode > 499)
                        {
                            return(LogEventLevel.Error);
                        }

                        return(duration < 1000 && context.Response.StatusCode < 400 ? LogEventLevel.Debug : LogEventLevel.Information);
                    });
                })
                .Configure(app => {
                    Bootstrapper.LogConfiguration(app.ApplicationServices, options, app.ApplicationServices.GetService <ILogger <Program> >());

                    if (!String.IsNullOrEmpty(options.ExceptionlessApiKey) && !String.IsNullOrEmpty(options.ExceptionlessServerUrl))
                    {
                        app.UseExceptionless(ExceptionlessClient.Default);
                    }

                    app.UseHealthChecks("/health", new HealthCheckOptions {
                        Predicate = hcr => !String.IsNullOrEmpty(jobOptions.JobName) ? hcr.Tags.Contains(jobOptions.JobName) : hcr.Tags.Contains("AllJobs")
                    });

                    app.UseHealthChecks("/ready", new HealthCheckOptions {
                        Predicate = hcr => hcr.Tags.Contains("Critical")
                    });

                    app.UseWaitForStartupActionsBeforeServingRequests();
                    app.Use((context, func) => context.Response.WriteAsync($"Running Job: {jobOptions.JobName}"));
                });

                var metricOptions = MetricOptions.ReadFromConfiguration(config);
                if (!String.IsNullOrEmpty(metricOptions.Provider))
                {
                    ConfigureMetricsReporting(webBuilder, metricOptions);
                }
            })
                          .ConfigureServices((ctx, services) => {
                AddJobs(services, jobOptions);
                services.AddAppOptions(options);

                if (useApplicationInsights)
                {
                    services.AddApplicationInsightsTelemetry(options.ApplicationInsightsKey);
                }

                Bootstrapper.RegisterServices(services);
                Insulation.Bootstrapper.RegisterServices(services, options, true);
            });

            return(builder);
        }
Ejemplo n.º 6
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(b => b.AddPolicy("AllowAny", p => p
                                              .AllowAnyHeader()
                                              .AllowAnyMethod()
                                              .SetIsOriginAllowed(isOriginAllowed: _ => true)
                                              .AllowCredentials()
                                              .SetPreflightMaxAge(TimeSpan.FromMinutes(5))
                                              .WithExposedHeaders("ETag", "Link", Headers.RateLimit, Headers.RateLimitRemaining, "X-Result-Count", Headers.LegacyConfigurationVersion, Headers.ConfigurationVersion)));

            services.Configure <ForwardedHeadersOptions>(options => {
                options.ForwardedHeaders      = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
                options.RequireHeaderSymmetry = false;
            });

            services.AddControllers(o => {
                o.Filters.Add <ApiExceptionFilter>();
                o.ModelBinderProviders.Insert(0, new CustomAttributesModelBinderProvider());
                o.InputFormatters.Insert(0, new RawRequestBodyFormatter());
            }).AddNewtonsoftJson(o => {
                o.SerializerSettings.DefaultValueHandling = DefaultValueHandling.Include;
                o.SerializerSettings.NullValueHandling    = NullValueHandling.Include;
                o.SerializerSettings.Formatting           = Formatting.Indented;
                o.SerializerSettings.ContractResolver     = Core.Bootstrapper.GetJsonContractResolver(); // TODO: See if we can resolve this from the di.
            });

            services.AddAuthentication(ApiKeyAuthenticationOptions.ApiKeySchema).AddApiKeyAuthentication();
            services.AddAuthorization(options => {
                options.DefaultPolicy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
                options.AddPolicy(AuthorizationRoles.ClientPolicy, policy => policy.RequireClaim(ClaimTypes.Role, AuthorizationRoles.Client));
                options.AddPolicy(AuthorizationRoles.UserPolicy, policy => policy.RequireClaim(ClaimTypes.Role, AuthorizationRoles.User));
                options.AddPolicy(AuthorizationRoles.GlobalAdminPolicy, policy => policy.RequireClaim(ClaimTypes.Role, AuthorizationRoles.GlobalAdmin));
            });

            services.AddRouting(r => {
                r.LowercaseUrls = true;
                r.ConstraintMap.Add("identifier", typeof(IdentifierRouteConstraint));
                r.ConstraintMap.Add("identifiers", typeof(IdentifiersRouteConstraint));
                r.ConstraintMap.Add("objectid", typeof(ObjectIdRouteConstraint));
                r.ConstraintMap.Add("objectids", typeof(ObjectIdsRouteConstraint));
                r.ConstraintMap.Add("token", typeof(TokenRouteConstraint));
                r.ConstraintMap.Add("tokens", typeof(TokensRouteConstraint));
            });
            services.AddSwaggerGen(c => {
                c.SwaggerDoc("v2", new OpenApiInfo {
                    Title   = "Exceptionless API",
                    Version = "v2"
                });

                c.AddSecurityDefinition("Basic", new OpenApiSecurityScheme {
                    Description = "Basic HTTP Authentication",
                    Scheme      = "basic",
                    Type        = SecuritySchemeType.Http
                });
                c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme {
                    Description = "Authorization token. Example: \"Bearer {apikey}\"",
                    Scheme      = "bearer",
                    Type        = SecuritySchemeType.Http
                });
                c.AddSecurityDefinition("Token", new OpenApiSecurityScheme {
                    Description = "Authorization token. Example: \"Bearer {apikey}\"",
                    Name        = "access_token",
                    In          = ParameterLocation.Query,
                    Type        = SecuritySchemeType.ApiKey
                });

                c.AddSecurityRequirement(new OpenApiSecurityRequirement {
                    {
                        new OpenApiSecurityScheme {
                            Reference = new OpenApiReference {
                                Type = ReferenceType.SecurityScheme, Id = "Basic"
                            }
                        },
                        new string[0]
                    },
                    {
                        new OpenApiSecurityScheme {
                            Reference = new OpenApiReference {
                                Type = ReferenceType.SecurityScheme, Id = "Bearer"
                            }
                        },
                        new string[0]
                    },
                    {
                        new OpenApiSecurityScheme {
                            Reference = new OpenApiReference {
                                Type = ReferenceType.SecurityScheme, Id = "Token"
                            }
                        },
                        new string[0]
                    }
                });

                if (File.Exists($@"{AppDomain.CurrentDomain.BaseDirectory}\Exceptionless.Web.xml"))
                {
                    c.IncludeXmlComments($@"{AppDomain.CurrentDomain.BaseDirectory}\Exceptionless.Web.xml");
                }

                c.IgnoreObsoleteActions();
            });

            var appOptions = AppOptions.ReadFromConfiguration(Configuration);

            Bootstrapper.RegisterServices(services, appOptions, Log.Logger.ToLoggerFactory());
            services.AddSingleton(s => {
                return(new ThrottlingOptions {
                    MaxRequestsForUserIdentifierFunc = userIdentifier => appOptions.ApiThrottleLimit,
                    Period = TimeSpan.FromMinutes(15)
                });
            });
        }
Ejemplo n.º 7
0
        public static IWebHostBuilder CreateWebHostBuilder(string[] args)
        {
            var jobOptions = new JobRunnerOptions(args);

            Console.Title = jobOptions.JobName != null ? $"Exceptionless {jobOptions.JobName} Job" : "Exceptionless Jobs";

            string environment = Environment.GetEnvironmentVariable("EX_AppMode");

            if (String.IsNullOrWhiteSpace(environment))
            {
                environment = "Production";
            }

            string currentDirectory = Directory.GetCurrentDirectory();
            var    config           = new ConfigurationBuilder()
                                      .SetBasePath(currentDirectory)
                                      .AddYamlFile("appsettings.yml", optional: true, reloadOnChange: true)
                                      .AddYamlFile($"appsettings.{environment}.yml", optional: true, reloadOnChange: true)
                                      .AddEnvironmentVariables("EX_")
                                      .AddCommandLine(args)
                                      .Build();

            var options = AppOptions.ReadFromConfiguration(config);

            var loggerConfig = new LoggerConfiguration().ReadFrom.Configuration(config);

            if (!String.IsNullOrEmpty(options.ExceptionlessApiKey))
            {
                loggerConfig.WriteTo.Sink(new ExceptionlessSink(), LogEventLevel.Verbose);
            }

            var serilogLogger = loggerConfig.CreateLogger();

            _logger = new SerilogLoggerFactory(serilogLogger).CreateLogger <Program>();

            var configDictionary = config.ToDictionary("Serilog");

            _logger.LogInformation("Bootstrapping Exceptionless {JobName} job(s) in {AppMode} mode ({InformationalVersion}) on {MachineName} with settings {@Settings}", jobOptions.JobName ?? "All", environment, options.InformationalVersion, Environment.MachineName, configDictionary);

            bool useApplicationInsights = !String.IsNullOrEmpty(options.ApplicationInsightsKey);

            var builder = WebHost.CreateDefaultBuilder(args)
                          .UseEnvironment(environment)
                          .UseConfiguration(config)
                          .UseDefaultServiceProvider((ctx, o) => {
                o.ValidateScopes = ctx.HostingEnvironment.IsDevelopment();
            })
                          .ConfigureKestrel(c => {
                c.AddServerHeader = false;
                //c.AllowSynchronousIO = false; // TODO: Investigate issue with JSON Serialization.
            })
                          .UseSerilog(serilogLogger, true)
                          .ConfigureServices((ctx, services) => {
                services.AddHttpContextAccessor();

                AddJobs(services, jobOptions);

                if (useApplicationInsights)
                {
                    services.AddApplicationInsightsTelemetry();
                }

                Bootstrapper.RegisterServices(services);
                var serviceProvider = services.BuildServiceProvider();
                Insulation.Bootstrapper.RegisterServices(serviceProvider, services, options, true);

                services.PostConfigure <HostFilteringOptions>(o => {
                    if (o.AllowedHosts == null || o.AllowedHosts.Count == 0)
                    {
                        // "AllowedHosts": "localhost;127.0.0.1;[::1]"
                        var hosts = ctx.Configuration["AllowedHosts"]?.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                        // Fall back to "*" to disable.
                        o.AllowedHosts = (hosts?.Length > 0 ? hosts : new[] { "*" });
                    }
                });

                services.AddSingleton <IOptionsChangeTokenSource <HostFilteringOptions> >(new ConfigurationChangeTokenSource <HostFilteringOptions>(ctx.Configuration));
                services.AddTransient <IStartupFilter, HostFilteringStartupFilter>();
            })
                          .Configure(app => {
                Bootstrapper.LogConfiguration(app.ApplicationServices, options, _logger);

                if (!String.IsNullOrEmpty(options.ExceptionlessApiKey) && !String.IsNullOrEmpty(options.ExceptionlessServerUrl))
                {
                    app.UseExceptionless(ExceptionlessClient.Default);
                }

                app.UseHealthChecks("/health", new HealthCheckOptions {
                    Predicate = hcr => !String.IsNullOrEmpty(jobOptions.JobName) ? hcr.Tags.Contains(jobOptions.JobName) : hcr.Tags.Contains("AllJobs")
                });

                app.UseHealthChecks("/ready", new HealthCheckOptions {
                    Predicate = hcr => hcr.Tags.Contains("Critical")
                });

                app.UseWaitForStartupActionsBeforeServingRequests();
                app.Use((context, func) => context.Response.WriteAsync($"Running Job: {jobOptions.JobName}"));
            });

            if (String.IsNullOrEmpty(builder.GetSetting(WebHostDefaults.ContentRootKey)))
            {
                builder.UseContentRoot(Directory.GetCurrentDirectory());
            }

            if (useApplicationInsights)
            {
                builder.UseApplicationInsights(options.ApplicationInsightsKey);
            }

            var metricOptions = MetricOptions.ReadFromConfiguration(config);

            if (!String.IsNullOrEmpty(metricOptions.Provider))
            {
                ConfigureMetricsReporting(builder, metricOptions);
            }

            return(builder);
        }
Ejemplo n.º 8
0
        public static IWebHostBuilder CreateWebHostBuilder(IConfiguration config, string environment)
        {
            Console.Title = "Exceptionless Web";

            var options = AppOptions.ReadFromConfiguration(config);

            var loggerConfig = new LoggerConfiguration().ReadFrom.Configuration(config);

            if (!String.IsNullOrEmpty(options.ExceptionlessApiKey))
            {
                loggerConfig.WriteTo.Sink(new ExceptionlessSink(), LogEventLevel.Verbose);
            }

            var serilogLogger = loggerConfig.CreateLogger();

            _logger = new SerilogLoggerFactory(serilogLogger).CreateLogger <Program>();

            var configDictionary = config.ToDictionary("Serilog");

            _logger.LogInformation("Bootstrapping Exceptionless Web in {AppMode} mode ({InformationalVersion}) on {MachineName} with settings {@Settings}", environment, options.InformationalVersion, Environment.MachineName, configDictionary);

            bool useApplicationInsights = !String.IsNullOrEmpty(options.ApplicationInsightsKey);

            var builder = WebHost.CreateDefaultBuilder()
                          .UseEnvironment(environment)
                          .UseConfiguration(config)
                          .UseDefaultServiceProvider((ctx, o) => {
                o.ValidateScopes = ctx.HostingEnvironment.IsDevelopment();
            })
                          .ConfigureKestrel(c => {
                c.AddServerHeader = false;
                // c.AllowSynchronousIO = false; // TODO: Investigate issue with JSON Serialization.

                if (options.MaximumEventPostSize > 0)
                {
                    c.Limits.MaxRequestBodySize = options.MaximumEventPostSize;
                }
            })
                          .UseSerilog(serilogLogger, true)
                          .ConfigureServices((ctx, services) => {
                services.AddSingleton(config);
                services.AddHttpContextAccessor();

                if (useApplicationInsights)
                {
                    services.AddSingleton <ITelemetryInitializer, ExceptionlessTelemetryInitializer>();
                    services.AddApplicationInsightsTelemetry();
                }

                services.PostConfigure <HostFilteringOptions>(o => {
                    if (o.AllowedHosts == null || o.AllowedHosts.Count == 0)
                    {
                        // "AllowedHosts": "localhost;127.0.0.1;[::1]"
                        var hosts = ctx.Configuration["AllowedHosts"]?.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                        // Fall back to "*" to disable.
                        o.AllowedHosts = (hosts?.Length > 0 ? hosts : new[] { "*" });
                    }
                });

                services.AddSingleton <IOptionsChangeTokenSource <HostFilteringOptions> >(new ConfigurationChangeTokenSource <HostFilteringOptions>(ctx.Configuration));
                services.AddTransient <IStartupFilter, HostFilteringStartupFilter>();
            })
                          .UseStartup <Startup>();

            if (String.IsNullOrEmpty(builder.GetSetting(WebHostDefaults.ContentRootKey)))
            {
                builder.UseContentRoot(Directory.GetCurrentDirectory());
            }

            if (useApplicationInsights)
            {
                builder.UseApplicationInsights(options.ApplicationInsightsKey);
            }

            var metricOptions = MetricOptions.ReadFromConfiguration(config);

            if (!String.IsNullOrEmpty(metricOptions.Provider))
            {
                ConfigureMetricsReporting(builder, metricOptions);
            }

            return(builder);
        }