public static IServiceCollection AddHealthFromConfiguration(
            this IServiceCollection serviceCollection,
            IConfiguration configuration, Action <IHealthBuilder> setup = null
            )
        {
            var cfg = configuration.GetTypedSection <HealthCheckMonitoring>();

            if (cfg == null || cfg.Enabled == false)
            {
                return(serviceCollection);
            }

            var serviceProvider = serviceCollection
                                  .BuildServiceProvider();

            var healthBuilder = AppMetricsHealth
                                .CreateDefaultBuilder();

            SetupChecks(cfg.Checks, healthBuilder);
            SetupReports(cfg.Reports, serviceProvider, healthBuilder);

            if (setup != null)
            {
                setup.Invoke(healthBuilder);
            }

            serviceCollection.AddHealthEndpoints();
            healthBuilder.BuildAndAddTo(serviceCollection);

            return(serviceCollection);
        }
Ejemplo n.º 2
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1).AddMetrics();

            services.AddScoped <IService, Service>();

            services.AddScoped <IRepository, Repository>();

            var metrics = AppMetricsHealth.CreateDefaultBuilder()
                          .HealthChecks.RegisterFromAssembly(services)
                          .BuildAndAddTo(services);

            services.AddHealth(metrics);

            services.AddHealthEndpoints();

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo
                {
                    Version     = "v1",
                    Title       = "Swagger - ToDo API",
                    Description = "Available Web APIs"
                });
            });
        }
Ejemplo n.º 3
0
        private IServiceProvider SetupServicesAndConfiguration(
            Action <HealthEndpointsOptions> setupEndpointAction = null)
        {
            var services = new ServiceCollection();

            services.AddOptions();

            var builder = new ConfigurationBuilder()
                          .SetBasePath(AppContext.BaseDirectory)
                          .AddJsonFile("DependencyInjection/TestConfiguration/appsettings.json", optional: true, reloadOnChange: true);

            var configuration = builder.Build();

            var healthBuilder = AppMetricsHealth.CreateDefaultBuilder()
                                .Configuration.ReadFrom(configuration);

            services.AddHealth(healthBuilder);

            if (setupEndpointAction == null)
            {
                services.AddHealthEndpoints(configuration.GetSection(nameof(HealthEndpointsOptions)));
            }
            else
            {
                services.AddHealthEndpoints(configuration.GetSection(nameof(HealthEndpointsOptions)), setupEndpointAction);
            }

            return(services.BuildServiceProvider());
        }
Ejemplo n.º 4
0
        public void ConfigureServices(IServiceCollection services)
        {
            InitializeDependencyInjection(services);

            services.AddAutoMapper();

            services.AddResponseCompression();

            var metrics = AppMetricsHealth.CreateDefaultBuilder()
                          .HealthChecks.RegisterFromAssembly(services)
                          .BuildAndAddTo(services);

            services.AddHealth(metrics);
            services.AddHealthEndpoints();

            services.AddMvc().AddJsonOptions(options =>
            {
                options.SerializerSettings.NullValueHandling =
                    Newtonsoft.Json.NullValueHandling.Ignore;
            });

            ResponseValidationErrorHandler(services);

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info {
                    Title = "Api Livros", Version = "v1"
                });
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            services.AddApiVersioning(o => o.ApiVersionReader = new HeaderApiVersionReader("api-version"));
        }
        public static IHostBuilder ConfigureHealthWithDefaults(
            this IHostBuilder hostBuilder,
            Action <HostBuilderContext, IServiceCollection, IHealthBuilder> configureHealth,
            DependencyContext dependencyContext = null)
        {
            if (_healthBuilt)
            {
                throw new InvalidOperationException("HealthBuilder allows creation only of a single instance of IHealth");
            }

            return(hostBuilder.ConfigureServices(
                       (context, services) =>
            {
                var healthBuilder = AppMetricsHealth.CreateDefaultBuilder();

                configureHealth(context, services, healthBuilder);

                healthBuilder.HealthChecks.RegisterFromAssembly(services, dependencyContext ?? GetDependencyContext());
                healthBuilder.Configuration.ReadFrom(context.Configuration);

                if (healthBuilder.CanReport())
                {
                    services.AddHealthReportingHostedService();
                }

                services.AddHealth(healthBuilder);

                _healthBuilt = true;
            }));
        }
Ejemplo n.º 6
0
        private static void Init(IServiceCollection services, IConfiguration configuration)
        {
            Configuration = configuration;

            //构建Metrics对象
            Metrics = BuildMetricsRoot();

            Health = BuildHealthRoot(AppMetricsHealth.CreateDefaultBuilder());
        }
Ejemplo n.º 7
0
        private static void AddObserverHealtEndpoints(this IServiceCollection services)
        {
            services.AddHealth(AppMetricsHealth
                               .CreateDefaultBuilder()
                               .HealthChecks
                               .RegisterFromAssembly(services)
                               .BuildAndAddTo(services));

            services.TryAddEnumerable(ServiceDescriptor.Singleton <IConfigureOptions <HealthEndpointsHostingOptions>, ObservableClientHealthHostingOptions>());
            services.AddHealthEndpoints();
        }
Ejemplo n.º 8
0
        public MetricsPlugin()
        {
            Metrics = new MetricsBuilder().Report.ToInfluxDb(options =>
            {
                options.InfluxDb.BaseUri  = new Uri("http://s1.pikachu.local:8086");
                options.InfluxDb.Database = "metrics";
            }).Build();

            Health = AppMetricsHealth.CreateDefaultBuilder().Configuration.Configure(c => { }).Build();

            MetricTasks = new List <IMetricTask>();
        }
Ejemplo n.º 9
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            var metrics = AppMetricsHealth.CreateDefaultBuilder()
                          .HealthChecks.RegisterFromAssembly(services)
                          .BuildAndAddTo(services);

            services
            .AddHealth(metrics)
            .AddHealthEndpoints();
        }
Ejemplo n.º 10
0
        private void ConfigureHealthChecks(IServiceCollection services)
        {
            var metrics = AppMetricsHealth.CreateDefaultBuilder()
                          //TODO .HealthChecks.AddCheck<>()
                          .BuildAndAddTo(services);

            services.AddHealthEndpoints(options =>
            {
                options.HealthEndpointEnabled         = true;
                options.PingEndpointEnabled           = true;
                options.HealthEndpointOutputFormatter = new HealthStatusJsonOutputFormatter();
            });
        }
Ejemplo n.º 11
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var metrics = AppMetrics.CreateDefaultBuilder().Build();
            var health  = AppMetricsHealth.CreateDefaultBuilder().HealthChecks.RegisterFromAssembly(services);

            services.AddMetrics(metrics);
            services.AddMetricsTrackingMiddleware();

            services.AddHealth(health);
            services.AddHealthEndpoints();

            services.AddDbContext <Models.ScoredNameContext>(opt => opt.UseInMemoryDatabase("IndexItems"), ServiceLifetime.Singleton);
            services.AddMvc(options => options.AddMetricsResourceFilter());
        }
Ejemplo n.º 12
0
        public void Can_resolve_health_from_service_collection_when_pre_built()
        {
            // Arrange
            var metrics  = AppMetricsHealth.CreateDefaultBuilder().Build();
            var services = new ServiceCollection();

            // Act
            services.AddHealth(metrics);

            // Assert
            var provider = services.BuildServiceProvider();

            provider.GetService <IHealthRoot>().Should().NotBeNull();
        }
Ejemplo n.º 13
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            services.AddRedis(Configuration.GetValue <string>("Redis"));
            services.AddMediatR();

            services.AddHealth(
                AppMetricsHealth.CreateDefaultBuilder()
                .HealthChecks.RegisterFromAssembly(services)
                .BuildAndAddTo(services));
            services.AddHealthEndpoints();
        }
        public static IServiceCollection AddCustomMetrics(this IServiceCollection services,
                                                          IConfiguration configuration)
        {
            services.Configure <KestrelServerOptions>(options => { options.AllowSynchronousIO = true; });

            var metrics = AppMetrics.CreateDefaultBuilder()
                          .OutputMetrics.AsJson()
                          .OutputMetrics.AsPrometheusPlainText()
                          .Configuration.ReadFrom(configuration)
                          .Build();

            var processMemoryGauge = new GaugeOptions
            {
                Name            = "Process Memory",
                MeasurementUnit = Unit.Bytes,
            };

            metrics.Measure.Gauge.SetValue(processMemoryGauge, new MetricTags("type", "physical"),
                                           () => Process.GetCurrentProcess().WorkingSet64);
            metrics.Measure.Gauge.SetValue(processMemoryGauge, new MetricTags("type", "private"),
                                           () => Process.GetCurrentProcess().PrivateMemorySize64);
            metrics.Measure.Gauge.SetValue(processMemoryGauge, new MetricTags("type", "virtual"),
                                           () => Process.GetCurrentProcess().VirtualMemorySize64);

            services.AddMvcCore().AddMetricsCore();
            services.AddMetrics(metrics);
            services.AddMetricsReportingHostedService();
            services.AddMetricsTrackingMiddleware(configuration);

            services.AddMetricsEndpoints(
                options => { options.MetricsTextEndpointOutputFormatter = new MetricsPrometheusTextOutputFormatter(); },
                configuration);


            AppMetricsHealth.CreateDefaultBuilder()
            .OutputHealth.AsJson()
            .HealthChecks.RegisterFromAssembly(services)
            .Configuration.ReadFrom(configuration)
            .Report.ToMetrics(metrics)
            .BuildAndAddTo(services);

            services.AddHealthEndpoints(
                options => { options.HealthEndpointOutputFormatter = new HealthStatusTextOutputFormatter(); },
                configuration);
            services.AddHealthReportingHostedService();

            return(services);
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        public virtual void ConfigureServices(IServiceCollection services)
        {
            //var dbContext = services.BuildServiceProvider().GetService<SampleDbContext>();

            AppMetricsHealth.CreateDefaultBuilder()
            //    .HealthChecks.AddCheck(new DatabaseHealthCheck(dbContext))
            .BuildAndAddTo(services);

            services.AddMvc(config =>
            {
                var policy = new AuthorizationPolicyBuilder()
                             .RequireAuthenticatedUser()
                             .Build();
                config.Filters.Add(new AuthorizeFilter(policy));
                config.ValueProviderFactories.Add(new SnakeCaseQueryStringValueProviderFactory());
            })
            .AddJsonOptions(json =>
            {
                json.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                json.SerializerSettings.ContractResolver      = new DefaultContractResolver
                {
                    NamingStrategy = new SnakeCaseNamingStrategy(true, false)
                };
            });

            services
            .AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
            .AddIdentityServerAuthentication(BindIdentityServerAuthenticationOptions);

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("docs", new Info {
                    Title = "Template Api", Version = "v1"
                });
                c.OperationFilter <SnakeCaseFilter>();
                c.AddSecurityDefinition("oauth2",
                                        new OAuth2Scheme
                {
                    Description = "Requests an authorization token from Identity Provider",
                    TokenUrl    = Configuration["IdentityProvider:Authority"] + "/connect/token",
                    Flow        = "application"
                });
                c.OperationFilter <OAuthFilter>();
            });

            services.AddAutoMapper();
        }
Ejemplo n.º 16
0
        public void ConfigureServices(IServiceCollection services)
        {
            services
            .AddMvc()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
            .AddJsonOptions(o => o.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver());

            services.AddRedis(Configuration.GetValue <string>("Redis"));
            services.AddNats(Configuration.GetValue <string>("Nats"));
            services.AddMediatR();

            services.AddHealth(
                AppMetricsHealth.CreateDefaultBuilder()
                .HealthChecks.RegisterFromAssembly(services)
                .BuildAndAddTo(services));
            services.AddHealthEndpoints();
        }
        /// <summary>
        /// Adds the default set of API components.
        /// </summary>
        /// <remarks>
        /// * AspNetCore MVC
        /// * Swagger API Spec Generation
        /// </remarks>
        /// <example>
        /// <code>
        /// // Default swaggerOptions
        /// options =>
        ///  {
        ///      options.DescribeAllEnumsAsStrings();
        ///      options.DescribeStringEnumsInCamelCase();
        ///      options.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info
        ///      {
        ///          Title = "HTTP API",
        ///          Version = "v1",
        ///          Description = "The Service HTTP API",
        ///      });
        ///  }
        /// </code>
        /// </example>
        /// <param name="services">The framework <see cref="IServiceCollection" /></param>
        /// <param name="container">The application composition root</param>
        /// <param name="env">
        /// The framework <see cref="IHostingEnvironment"/> used to
        /// determine whether to enable environment-specific middleware
        /// </param>
        /// <param name="useSwagger">
        /// Optional: Specify `true` to enable Swagger API Spec generation using Swashbuckle.AspNetCore.
        /// (Default: `true`)
        /// </param>
        /// <param name="swaggerOptions">
        /// Optional: An <c>Action</c> of type <see cref="Action{SwaggerGenOptions}" /> used to configure
        /// Swagger spec generation.
        /// (Default: see Remarks for default action)
        /// </param>
        /// <param name="configureHealthCheck">
        /// Optional: An <c>Func</c> of type <see cref="Func{IHealthBuilder, IHealthBuilder}" /> used to configure
        /// health checks.</param>
        /// <returns>The <see cref="IMvcBuilder" /> used to configure Mvc</returns>
        public static IMvcBuilder AddDefaultApiServices(
            this IServiceCollection services,
            Container container,
            IHostingEnvironment env,
            bool useSwagger = true,
            Action <SwaggerGenOptions> swaggerOptions = null,
            Func <IHealthBuilder, IHealthBuilder> configureHealthCheck = null
            )
        {
            // Redirect framework logging to Serilog logger
            services.AddSingleton <ILoggerFactory>(_ => new SerilogLoggerFactory(null, true));

            container.Register <RequestLoggingMiddleware>(Lifestyle.Scoped);

            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();

            if (env.IsDevelopment())
            {
                // https://andrewlock.net/understanding-your-middleware-pipeline-with-the-middleware-analysis-package/
                services.AddMiddlewareAnalysis();
            }

            container.AddCorrelationId();
            services.AddCorrelationId();

            if (useSwagger)
            {
                services.AddSwaggerGen(swaggerOptions ?? ConfigureSwaggerGenDefaults(container));
            }

            configureHealthCheck = configureHealthCheck ?? (o => o);
            configureHealthCheck(AppMetricsHealth.CreateDefaultBuilder()
                                 .HealthChecks.RegisterFromAssembly(services, DependencyContext.Default))
            .BuildAndAddTo(services);
            services.AddHealthEndpoints();

            services.AddResponseCompression(options =>
            {
                options.EnableForHttps = true;
                options.Providers.Add <GzipCompressionProvider>();
            });

            return(services
                   .AddMvc()
                   .AddDefaultJsonConfiguration());
        }
Ejemplo n.º 18
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddHttpContextAccessor();
            services.AddCorrelationId();
            services.AddMvcCore()
            .AddJsonFormatters();

            var healthMetrics = AppMetricsHealth.CreateDefaultBuilder()
                                .BuildAndAddTo(services);

            services.AddHealth(healthMetrics);
            services.AddHttpClient();

            services.AddTransient <LoggingHandler>();

            ConfigureServiceCollection(services);
        }
Ejemplo n.º 19
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton <IConfiguration>(ConfigurationExtensions.Current);
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            services.AddAntiforgery(options => { options.SuppressXFrameOptionsHeader = false; });

            const long threshold = 7000000000;                 // ~7 GB
            const long thresholdVirtualMemory = 2560000000000; // ~256 GB

            AppMetricsHealth.CreateDefaultBuilder()
            .HealthChecks.AddProcessPrivateMemorySizeCheck("Private Memory Size", threshold, true)
            .HealthChecks.AddProcessVirtualMemorySizeCheck("Virtual Memory Size", thresholdVirtualMemory, true)
            .HealthChecks.AddProcessPhysicalMemoryCheck("Working Set", threshold, true)
            .BuildAndAddTo(services);
            services.AddMvc();

            AddMvc(services);
        }
Ejemplo n.º 20
0
        private static void Init()
        {
            var builder = new ConfigurationBuilder()
                          .SetBasePath(Directory.GetCurrentDirectory())
                          .AddJsonFile("appsettings.json");

            Configuration = builder.Build();

            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Verbose()
                         .WriteTo.LiterateConsole()
                         .WriteTo.Seq("http://localhost:5341")
                         .CreateLogger();

            Health = AppMetricsHealth.CreateDefaultBuilder()
                     .HealthChecks.AddCheck(new SampleHealthCheck())
                     .HealthChecks.AddProcessPrivateMemorySizeCheck("Private Memory Size", 200)
                     .HealthChecks.AddProcessVirtualMemorySizeCheck("Virtual Memory Size", 200)
                     .HealthChecks.AddProcessPhysicalMemoryCheck("Working Set", 200)
                     .HealthChecks.AddPingCheck("google ping", "google.com", TimeSpan.FromSeconds(10))
                     .HealthChecks.AddHttpGetCheck("invalid http", new Uri("https://invalid-asdfadsf.com/"), 3, TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1))
                     .HealthChecks.AddHttpGetCheck("github", new Uri("https://github.com/"), retries: 3, delayBetweenRetries: TimeSpan.FromMilliseconds(100), timeoutPerRequest: TimeSpan.FromSeconds(5))
                     .HealthChecks.AddHttpGetCheck("google", new Uri("https://google.com/"), TimeSpan.FromSeconds(1))
                     .HealthChecks.AddCheck("DatabaseConnected", () => new ValueTask <HealthCheckResult>(HealthCheckResult.Healthy("Database Connection OK")))
                     .HealthChecks.AddCheck(
                "DiskSpace",
                () =>
            {
                var freeDiskSpace = GetFreeDiskSpace();
                return(new ValueTask <HealthCheckResult>(
                           freeDiskSpace <= 512
                                ? HealthCheckResult.Unhealthy("Not enough disk space: {0}", freeDiskSpace)
                                : HealthCheckResult.Unhealthy("Disk space ok: {0}", freeDiskSpace)));
            })
                     .HealthChecks.AddSqlCheck("DB Connection", () => new SqliteConnection(ConnectionString), TimeSpan.FromSeconds(10))
                     .Build();

            int GetFreeDiskSpace()
            {
                return(1024);
            }
        }
Ejemplo n.º 21
0
        protected async override ValueTask <HealthCheckResult> CheckAsync(CancellationToken cancellationToken = default(CancellationToken))
        {
            if (healthCheck == null)
            {
                var addresses = server.Features.Get <IServerAddressesFeature>().Addresses;
                if (!addresses.Any())
                {
                    return(HealthCheckResult.Unhealthy());
                }
                healthCheck = AppMetricsHealth.CreateDefaultBuilder()
                              .HealthChecks.AddHttpGetCheck("local", new Uri(addresses
                                                                             .First()
                                                                             .Replace("[::]", "localhost")
                                                                             ), TimeSpan.FromSeconds(5), degradedOnError: true)
                              .Build()
                              .Checks.First();
            }

            return((await healthCheck.ExecuteAsync(cancellationToken)).Check);
        }
Ejemplo n.º 22
0
        public static IWebHostBuilder ConfigureHealthWithDefaults(
            this IWebHostBuilder hostBuilder,
            Action <WebHostBuilderContext, IHealthBuilder> configureHealth)
        {
            if (_healthBuilt)
            {
                throw new InvalidOperationException("HealthBuilder allows creation only of a single instance of IMetrics");
            }

            return(hostBuilder.ConfigureServices(
                       (context, services) =>
            {
                var healthBuilder = AppMetricsHealth.CreateDefaultBuilder();
                configureHealth(context, healthBuilder);
                healthBuilder.HealthChecks.RegisterFromAssembly(services, Assembly.GetEntryAssembly().GetName().Name);
                healthBuilder.Configuration.ReadFrom(context.Configuration);
                healthBuilder.BuildAndAddTo(services);
                _healthBuilt = true;
            }));
        }
Ejemplo n.º 23
0
        private static void Init()
        {
            var builder = new ConfigurationBuilder()
                          .SetBasePath(Directory.GetCurrentDirectory())
                          .AddJsonFile("appsettings.json");

            Configuration = builder.Build();

            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Verbose()
                         .WriteTo.LiterateConsole()
                         .WriteTo.Seq("http://*****:*****@"UseDevelopmentStorage=true");

            var eventHubConnectionString   = "todo event hub connection string";
            var eventHubName               = "todo event hub name";
            var serviceBusConnectionString = "todo sb connection string";
            var queueName = "todo queue name";
            var topicName = "todo topic name";

            Health = AppMetricsHealth.CreateDefaultBuilder()
                     .HealthChecks.AddAzureBlobStorageConnectivityCheck("Blob Storage Connectivity Check", storageAccount)
                     .HealthChecks.AddAzureBlobStorageContainerCheck("Blob Storage Container Check", storageAccount, containerName)
                     .HealthChecks.AddAzureQueueStorageConnectivityCheck("Queue Storage Connectivity Check", storageAccount)
                     .HealthChecks.AddAzureQueueStorageCheck("Queue Storage Check", storageAccount, "test")
                     .HealthChecks.AddAzureDocumentDBDatabaseCheck("DocumentDB Database Check", documentDbDatabaseUri, documentDbUri, doucmentDbKey)
                     .HealthChecks.AddAzureDocumentDBCollectionCheck("DocumentDB Collection Check", collectionUri, documentDbUri, doucmentDbKey)
                     .HealthChecks.AddAzureTableStorageConnectivityCheck("Table Storage Connectivity Check", storageAccount)
                     .HealthChecks.AddAzureTableStorageTableCheck("Table Storage Table Exists Check", storageAccount, "test")
                     .HealthChecks.AddAzureEventHubConnectivityCheck("Service EventHub Connectivity Check", eventHubConnectionString, eventHubName)
                     .HealthChecks.AddAzureServiceBusQueueConnectivityCheck("Service Bus Queue Connectivity Check", serviceBusConnectionString, queueName)
                     .HealthChecks.AddAzureServiceBusTopicConnectivityCheck("Service Bus Topic Connectivity Check", serviceBusConnectionString, topicName)
                     .Build();
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var metrics = new MetricsBuilder()
                          .Report.ToInfluxDb(options =>
            {
                options.InfluxDb.BaseUri  = new Uri("http://influxdb:8086");
                options.InfluxDb.Database = "appmetrics";
                options.InfluxDb.UserName = "******";
                options.InfluxDb.Password = "******";
            })
                          .Build();

            var health = AppMetricsHealth.CreateDefaultBuilder().Configuration.Configure(new HealthOptions()
            {
                Enabled = true, ApplicationName = "http://health.local.com", ReportingEnabled = true
            })
                         .Report.ToMetrics(metrics)
                         .HealthChecks.AddSqlCachedCheck("Teste de conexão com o banco.", () => new MySql.Data.MySqlClient.MySqlConnection("Server=mysql;Database=healthcheck;Uid=healthcheckuser;Pwd=healthcheckpws;SslMode=none;"),
                                                         TimeSpan.FromSeconds(10),
                                                         TimeSpan.FromMinutes(1))
                         .HealthChecks.AddPingCheck("Google Ping", "google.com", TimeSpan.FromSeconds(10))
                         .HealthChecks.AddHttpGetCheck("GitHub", new Uri("https://github.com"), TimeSpan.FromSeconds(10))
                         .BuildAndAddTo(services);

            services.AddHealth(health);
            services.AddHealthEndpoints();

            services.AddMetrics(metrics);

            // ASP.NET CORE 2.1
            // Metricas
            services.AddMetricsReportingHostedService();
            // Healthcheck
            services.AddHealthReportingHostedService();

            services.AddMetricsTrackingMiddleware();

            services.AddMvc().AddMetrics();

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }
Ejemplo n.º 25
0
        public static IWebHostBuilder ConfigureHealth(this IWebHostBuilder hostBuilder)
        {
            if (_healthBuilt)
            {
                return(hostBuilder);
            }

            return(hostBuilder.ConfigureServices(
                       (context, services) =>
            {
                if (!_healthBuilt)
                {
                    AppMetricsHealth.CreateDefaultBuilder()
                    .Configuration.ReadFrom(context.Configuration)
                    .HealthChecks.RegisterFromAssembly(services, Assembly.GetEntryAssembly().GetName().Name)
                    .BuildAndAddTo(services);

                    _healthBuilt = true;
                }
            }));
        }
        public static IHostBuilder ConfigureHealth(
            this IHostBuilder hostBuilder,
            DependencyContext dependencyContext = null)
        {
            if (_healthBuilt)
            {
                return(hostBuilder);
            }

            return(hostBuilder.ConfigureServices(
                       (context, services) =>
            {
                if (!_healthBuilt)
                {
                    var builder = AppMetricsHealth.CreateDefaultBuilder().Configuration.ReadFrom(context.Configuration).HealthChecks.
                                  RegisterFromAssembly(services, dependencyContext ?? GetDependencyContext());

                    services.AddHealth(builder);
                    _healthBuilt = true;
                }
            }));
        }
Ejemplo n.º 27
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var metrics = new MetricsBuilder()
                          .Configuration.Configure(
                options =>
            {
                options.AddServerTag();
                options.AddEnvTag();
                options.AddAppTag();
            })
                          .OutputMetrics.AsPrometheusPlainText()
                          .Build();

            services.AddMetrics(metrics);

            var health = AppMetricsHealth.CreateDefaultBuilder()//.Configuration.Configure(new HealthOptions() { Enabled = true, ApplicationName = "http://health.local.com", ReportingEnabled = true })
                         .Report.ToMetrics(metrics)
                         .HealthChecks.AddSqlCachedCheck("Teste de conexão com o banco.", () => new MySql.Data.MySqlClient.MySqlConnection("Server=mysql;Database=healthcheck;Uid=healthcheckuser;Pwd=healthcheckpws;SslMode=none;"),
                                                         TimeSpan.FromSeconds(10),
                                                         TimeSpan.FromMinutes(1))
                         .HealthChecks.AddPingCheck("Google Ping", "google.com", TimeSpan.FromSeconds(10))
                         .HealthChecks.AddHttpGetCheck("GitHub", new Uri("https://github.com"), TimeSpan.FromSeconds(10))
                         .HealthChecks.RegisterFromAssembly(services)
                         .BuildAndAddTo(services);

            services.AddMetricsReportingHostedService();
            services.AddHealthReportingHostedService();

            services.AddHealth(health);

            services.AddMetricsEndpoints();
            services.AddHealthEndpoints();
            services.AddMetricsTrackingMiddleware();
            services.AddMvc().AddMetrics();

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }
Ejemplo n.º 28
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            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 metrics = new MetricsBuilder()
                          .Configuration.Configure(
                options =>
            {
                options.AddServerTag();
                options.AddEnvTag();
                options.AddAppTag();
            })
                          .OutputMetrics.AsPrometheusPlainText()
                          .Build();

            services.AddMetrics(metrics);

            var health = AppMetricsHealth.CreateDefaultBuilder().Report.ToMetrics(metrics).BuildAndAddTo(services);

            services.AddMetricsReportingHostedService();
            services.AddHealthReportingHostedService();

            services.AddHealth(health);

            services.AddMetricsEndpoints();
            services.AddHealthEndpoints();
            services.AddMetricsTrackingMiddleware();
            services.AddMvc().AddMetrics();

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }
Ejemplo n.º 29
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var connectionString = Configuration["Data:DefaultConnection:ConnectionString"];

            Core.Startup.ConfigureServices(services, connectionString);

            services.AddMvc()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
            .AddFluentValidation(cfg => cfg.RegisterValidatorsFromAssemblyContaining <Startup>());

            Mapper.Initialize(x => x.AddProfile <MappingProfile>());
            services.AddSignalR();
            services.AddAutoMapper();

            var metrics = AppMetricsHealth.CreateDefaultBuilder()
                          .HealthChecks.RegisterFromAssembly(services)
                          .BuildAndAddTo(services);

            services.AddHealth(metrics);
            services.AddHealthEndpoints();
            services.AddMemoryCache();

            services.AddDbContext <MainContext>(options => options.UseSqlServer(connectionString));
        }
Ejemplo n.º 30
0
        public void ConfigureServices(IServiceCollection services)
        {
            #region Metrics监控配置
            string IsOpen = Configuration.GetSection("InfluxDB:IsOpen").Value.ToLower();
            if (IsOpen == "true")
            {
                string database       = Configuration.GetSection("InfluxDB")["DataBaseName"];
                string InfluxDBConStr = Configuration.GetSection("InfluxDB")["ConnectionString"];
                string app            = Configuration.GetSection("InfluxDB")["app"];
                string env            = Configuration.GetSection("InfluxDB")["env"];
                string username       = Configuration.GetSection("InfluxDB")["username"];
                string password       = Configuration.GetSection("InfluxDB")["password"];
                var    uri            = new Uri(InfluxDBConStr);

                var metrics = AppMetrics.CreateDefaultBuilder()
                              .Configuration.Configure(
                    options =>
                {
                    options.AddAppTag(app);
                    options.AddEnvTag(env);
                })
                              .Report.ToInfluxDb(
                    options =>
                {
                    options.InfluxDb.BaseUri  = uri;
                    options.InfluxDb.Database = database;
                    options.InfluxDb.UserName = username;
                    options.InfluxDb.Password = password;
                    options.InfluxDb.CreateDataBaseIfNotExists = true;
                    options.HttpPolicy.BackoffPeriod           = TimeSpan.FromSeconds(30);
                    options.HttpPolicy.FailuresBeforeBackoff   = 5;
                    options.HttpPolicy.Timeout = TimeSpan.FromSeconds(10);
                    options.FlushInterval      = TimeSpan.FromSeconds(5);
                })
                              .Build();


                services.AddMetrics(metrics);
                services.AddMetricsReportingHostedService();
                services.AddMetricsTrackingMiddleware();
                services.AddMetricsEndpoints();

                var hmetrics = AppMetricsHealth.CreateDefaultBuilder().Report.ToMetrics(metrics)
                               //.HealthChecks.RegisterFromAssembly(services)    //自定义注册
                               .HealthChecks.AddCheck(new MyHealthCheck("自定义类现"))
                               .HealthChecks.AddCheck("委括实现", () =>
                {
                    if (DateTime.Now.Second % 3 != 0)
                    {
                        return(new ValueTask <HealthCheckResult>(HealthCheckResult.Healthy("Ok")));
                    }
                    else
                    {
                        return(new ValueTask <HealthCheckResult>(HealthCheckResult.Unhealthy("error")));
                    }
                })
                               .BuildAndAddTo(services);
                services.AddHealth(hmetrics);
                services.AddHealthReportingHostedService();
                services.AddHealthEndpoints();
            }

            #endregion

            services.AddMvc().AddMetrics().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }