.Net Core 2.0+ InfluxDB+Grafana+App Metrics 实现跨平台的实时性能监控

最近这段时间一直在忙,没时间写博客,负责了一个项目,从前端到后端一直忙,同时还有其他第几个项目的系统架构要处理。

去年就开始关注net core了,只是平时写写demo,没用在项目中,正好这次机会就用了net core,具体是什么时候开始的不太记得了,总之刚开始是用core 1.0开发,然后在开发的时候突然想到,平时我们的项目中都没有做过项目的实时监控,为什么这次不试试看呢,而且还能知道每天什么时段的流量走向,系统吞吐量等。记得之前去北京总公司的时候,看到java开发部那边有一个大屏幕,实时的显示项目的吞吐量、请求量等信息,感觉非常酷,我们net应该可以可以实现吧。

抱着这总心态就去找了一些相关资料,也就在项目用了起来。

项目部署在windows环境下,Influxdb的介绍这里不再赘述。

1、首先安装InfluxDB时序数据库,地址如下:https://portal.influxdata.com/downloads#influxdb ,这里我就下载Windows Binaries (64-bit),具体的写一下配置文件和安装过程。

解压后打开influxdb.conf,因为influxdb的默认配置全是针对linux配置的,所以我们需要修改一下配置文件。

修改下面3个liunx的路径,改为winodws路径如下:

[meta]
  # Where the metadata/raft database is stored
  dir = "influxdb/meta"
[data]
  # The directory where the TSM storage engine stores TSM files.
  dir = "influxdb/data"
  # The directory where the TSM storage engine stores WAL files.
  wal-dir = "influxdb/wal"

我将influxdb的文件都放在了influxdb目录下,可以用相对位置,也可以用绝对位置,这个可以根据个人需要修改。

这里提一下,Influxdb v1.2.4之后好像网页图形化管理界面就去掉了,1.2.4之前的是有网页图形化管理界面的,influxdb.conf文件之前还有

[admin]
  # Determines whether the admin service is enabled.
   enabled = true

  # The default bind address used by the admin service.
   bind-address = ":8083"

不过后面的版本,conf文件里就没有这个了,所以大家要注意一下。后面版本没办法用网页图形化管理,如果要连接Influxdb的话可以在目录下以cmd运行influx.exe,如果不想所有人都可以访问你的InfluxDB,那么你可以在conf文件里配置认证信息

# Determines whether HTTP endpoint is enabled.
enabled = true

# The bind address used by the HTTP service.
bind-address = ":8086"

# Determines whether user authentication is enabled over HTTP/HTTPS.
auth-enabled = true

最后cmd运行,进入到你的解压目录,执行命令:

influxd -config influxdb.conf

这里说一下,使用influx.exe登录时,输入以下命令:influx -host 127.0.0.1 -port 8086 -username "admin" -password "123456",这样就连上InfluxDB了。然后创建数据库:CREATE DATABASE "AppMetricsDemo"。

如果你觉得这样比较麻烦,可以安装两个influxDB,一个是V1.2.4版的,一个是最新版的,这是需要修改配置文件的端口,将两个influxDB的端口修改成不一样的就好,然后用1.2.4版本的连接最新版的即可,如图,点击右上角的齿轮图标即可出现连接表单,

(安装好influxDB后,记得在influxDB中创建Demo需要的数据库“AppMetricsDemo”)

2、安装Grafana,下载地址:https://grafana.com/get,我们解压后进入bin目录,如图:

直接运行grafana-server.exe即可。

Grafana默认会监听3000的端口,所以我们进入http://localhost:3000,

会让你登陆,直接输入本地的管理员帐户即可,帐户:admin  密码:admin,进入后如图:

安装完成之后,我们下载相关仪表模版的Json文件。

地址如下:https://grafana.com/dashboards/2125

然后我们导入我们的仪表:如图操作即可

添加我们上面的数据源,如图:

选择Add DataSource,然后操作如下:

这样,我们就完成了Grafana的安装配置和添加数据源。

由于实际项目中,我们不可能在服务器上运行个控制台去开启这些服务,所以我们需要将influxDB和Grafana发布成服务的形式运行在服务器上,这里我们可以使用nssm工具将InfluxDB和Grafana封装成服务运行。

下载地址如下:http://www.nssm.cc/download

解压后进入到对应系统版本文件夹中,里面有个32位和64位的文件,根据自己的实际情况选择,如图:

我们选择win64,进入文件夹后运行cmd,输入nssm install InfluxDB 运行后出现如下界面:

重点说一下参数这一栏,Argument里输入:-config influxdb.conf,类似上面在cmd中输入Influxd -config influxdb.conf

安装好后运行起来就好,Grafana的安装类似上面的操作,只是Argument这一栏不需要输入任何东西。

3、.netCore 中使用AppMetrics,新建一个名为Demo 的api,然后编辑右键编辑 Demo.csproj文件,在ItemGroup节点下新增以下Package

<PackageReference Include="App.Metrics" Version="2.0.0-alpha" />
<PackageReference Include="App.Metrics.AspNetCore.Endpoints" Version="2.0.0-alpha" />
<PackageReference Include="App.Metrics.AspNetCore.Reporting" Version="2.0.0-alpha" />
<PackageReference Include="App.Metrics.AspNetCore.Tracking" Version="2.0.0-alpha" />
<PackageReference Include="App.Metrics.Extensions.Reporting.InfluxDB" Version="1.2.0" />
<PackageReference Include="App.Metrics.Formatters.Json" Version="2.0.0-alpha" />
<PackageReference Include="App.Metrics.Reporting.InfluxDB" Version="2.0.0-alpha" />

保存后,项目就引用了AppMetrics相关类库

然后修改appsettings.json文件。添加如下代码

{
  "Logging": {
    "IncludeScopes": false,
    "Debug": {
      "LogLevel": {
        "Default": "Warning"
      }
    },
    "Console": {
      "LogLevel": {
        "Default": "Warning"
      }
    }
  },
  "InfluxDB": {
    "IsOpen": true,
    "DataBaseName": "AppMetricsDemo",
    "ConnectionString": "http://10.10.134.109:8086",
    "username": "admin",
    "password": "123456",
    "app": "RepairApp",
    "env": "stage"
  }
}

ConfigureServices方法,如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using App.Metrics;

namespace Demo
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            #region Metrics监控配置
            string IsOpen = Configuration.GetSection("InfluxDB")["IsOpen"].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.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.AddMetricsReportScheduler();
                services.AddMetricsTrackingMiddleware();
                services.AddMetricsEndpoints();

            }
            #endregion

            services.AddMvc();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            #region 注入Metrics
            string IsOpen = Configuration.GetSection("InfluxDB")["IsOpen"].ToLower();
            if (IsOpen == "true")
            {
                app.UseMetricsAllMiddleware();
                // Or to cherry-pick the tracking of interest
                app.UseMetricsActiveRequestMiddleware();
                app.UseMetricsErrorTrackingMiddleware();
                app.UseMetricsPostAndPutSizeTrackingMiddleware();
                app.UseMetricsRequestTrackingMiddleware();
                app.UseMetricsOAuth2TrackingMiddleware();
                app.UseMetricsApdexTrackingMiddleware();

                app.UseMetricsAllEndpoints();
                // Or to cherry-pick endpoint of interest
                app.UseMetricsEndpoint();
                app.UseMetricsTextEndpoint();
                app.UseEnvInfoEndpoint();
            }
            #endregion

            app.UseMvc();
        }
    }
}

代码这一块基本上完成了。

接下来运行项目,访问以下,然后看看Grafana中的仪表盘看看

附上demo地址:https://github.com/landonzeng/AppMetricsDemo

时间: 2024-07-30 21:53:03

.Net Core 2.0+ InfluxDB+Grafana+App Metrics 实现跨平台的实时性能监控的相关文章

ASP.NET Core之跨平台的实时性能监控(2.健康检查)

前言 上篇我们讲了如何使用App Metrics 做一个简单的APM监控,最后提到过健康检查这个东西. 这篇主要就是讲解健康检查的内容. 没看过上篇的,请移步:ASP.NET Core之跨平台的实时性能监控 首先我们来了解一下什么是健康检查(health checks)? 1.什么是健康检查? 健康检查,其实这个名称已经很明确了,它是检查你的应用程序是否健康运行的一种方式.随着当前各类项目越来越多的应用程序正在转向微服务式架构,健康检查就变得尤为关键.虽然微服务体系结构具有许多好处,但其中一个缺

ASP.NET Core之跨平台的实时性能监控

应用程序的8个关键性能指标以及测量方法 最后卖了个小关子,是关于如何监控ASP.NET Core的. 今天我们就来讲讲如何监控它,下面上效果图: 阅读本文需要了解的相关技术与内容: InfluxDb(分布式时序数据库,开源)(注:分布式部分已商业化最新的分布式版本已不在开源,单例的继续开源) Grafana(开源的,功能齐全的度量仪表盘和图形编辑器) App Metrics(主角,开源的支持.NET Core的监控插件,采用管道注入的方式,对代码的入侵性极小) 本文测试环境为Windows64位

asp.net core api网关 实时性能监控

asp.net core api网关 实时性能监控 使用InfluxDB.Grafana Dockerfile 运行 InfluxDB.Grafana influxdb: image: influxdb ports: - "8086:8086" - "8083:8083" environment: - INFLUXDB_DB=TogetherAppMetricsDB - INFLUXDB_ADMIN_ENABLED=true - INFLUXDB_ADMIN_USE

Pepper Metrics - Spring/Spring Boot应用性能监控利器

关于项目 Pepper Metrics是我与同事开发的一个开源工具(https://github.com/zrbcool/pepper-metrics),其通过收集jedis/mybatis/httpservlet/dubbo/motan的运行性能统计,并暴露成prometheus等主流时序数据库兼容数据,通过grafana展示趋势.其插件化的架构也非常方便使用者扩展并集成其他开源组件. 请大家给个star,同时欢迎大家成为开发者提交PR一起完善项目. Architecture Pepper M

ASP.NET Core 1.0 基础与应用启动

.NET Core http://dotnet.github.io/[https://github.com/dotnet/coreclr] ASP.NET Core 1.0 https://get.asp.net/ Documentation:https://docs.asp.net/en/latest/index.html MVC:https://docs.asp.net/projects/mvc/en/latest/overview.html EF: http://docs.efprojec

为什么你需要将代码迁移到ASP.NET Core 2.0?

随着 .NET Core 2.0 的发布,.NET 开源跨平台迎来了新的时代.开发者们可以选择使用命令行.个人喜好的文本编辑器.Visual Studio 2017 15.3 和 Visual Studio Code 来开发自己的 .NET Core 2.0 项目.同时,微软 .NET 开发工具组也宣布了 ASP.NET Core 2.0 的发布,并且此版本与 .NET Core 2.0.Visual Studio 2017 15.3 和新的 Razor Pages 页面优化范例兼容.相信目前技

译 .NET Core 3.0 发布

原文:<Announcing .NET Core 3.0> 宣布.NET Core 3.0 发布 很高兴宣布.NET Core 3.0的发布.它包括许多改进,包括添加Windows窗体和WPF,添加新的JSON API,对ARM64的支持以及全面提高的性能. C# 8 也是此发行版的一部分,其中包括可为空,异步流和更多模式.包含F#4.7,专注于放宽语法并定位.NET Standard 2.0.可以立即开始将现有项目更新为目标.NET Core 3.0.该版本与以前的版本兼容,从而使更新变得容

asp.netCore3.0 中使用app.UseMvc() 配置路由

一.新配置路由策略  在 Asp.Net Core 3.0中默认不再支持app.UserMvc() 方式配置路由 系统. 而是使用新的模式,点击查看asp.netCore3.0区域和路由配置变化 默认使用的话 会抛出异常: InvalidOperationException: Endpoint Routing does not support 'IApplicationBuilder.UseMvc(...)'. To use 'IApplicationBuilder.UseMvc' set 'M

.NET Core使用App.Metrics监控消息队列(一):初探

一.简介 App Metrics是一个开放源代码和跨平台的.NET库,用于记录应用程序中的指标.App Metrics可以在.NET Core或也支持.NET 4.5.2的完整.NET框架上运行. App Metrics通过在内存中进行采样和聚合,并提供可扩展性点以指定间隔将指标刷新到存储库中,从而抽象化了Metrics的基础存储库,例如InfluxDB,Prometheus,Graphite,Elasticsearch等. App Metrics提供了各种度量标准类型来度量事物,例如请求率,计