.NETCore微服务探寻(三)

前言

一直以来对于.NETCore微服务相关的技术栈都处于一个浅尝辄止的了解阶段,在现实工作中也对于微服务也一直没有使用的业务环境,所以一直也没有整合过一个完整的基于.NETCore技术栈的微服务项目。正好由于最近刚好辞职,有了时间可以写写自己感兴趣的东西,所以在此想把自己了解的微服务相关的概念和技术框架使用实现记录在一个完整的工程中,由于本人技术有限,所以错误的地方希望大家指出。

目录

项目地址:https://github.com/yingpanwang/fordotnet/tree/dev

为什么需要分布式日志

在项目的运行运行过程中,不可避免的是由于系统原因或者业务原因产生的警告或异常,这时我们需要根据产生的异常或警告信息快速排查出现的问题并修复,但是由于多个服务产生的过于庞杂的信息使那些以往通过直接写入日志文件的方式已经无法满足快速排查的需求了,因为直接写入日志文件只能根据事先制定好的规则查看日志信息,但是由于体量过大导致排查起来异常麻烦,例如,如果问题出现在 6月20日的凌晨1点 日志文件对应的是 log-2020-06-20 ,那么导致这个问题产生的原因可能20日之前的前置问题已经产生,如果我们需要排查的话,由于无法宏观分析问题的出现原因,那么需要日志文件逐个查看导致效率低下。

如果采用分布式日志的话,首先由于日志由日志中心统一存储,不需要写入本地文件减少了IO(不包括由于项目与日志收集中心通讯失败而导致本地补偿产生的日志),其次搭配其他的可视乎,管理,分析组件,可以有一个良好的日志管理与可视化,排查时可以通过相关的信息筛选,过滤无关信息,从宏观信息中精准查询指定信息,从而提高排查效率。

怎么给项目接入分布式日志系统

  • Exceptionless Asp.Net Core 开源分布式日志组件

  • Log组件+ Elasticsearch+ Kibana 这种模式采用的时通过扩展已有日志组件(Log4Net,Serilog,NLog等),通过Elasticsearch使用或不适用队列的模式收集日志,然后通过Kibana可视化管理分析组件 实现日志的收集分析

    目前我所了解的搭建分布式日志系统的方式有两种,但他们的方式其实底层都差不多 主要依赖Elasticsearch作为日志的收集,然后搭配可视化的插件,这里我选择的时采用的是第二种方式,因为对代码的侵入性较小,可以比较灵活的根据实际的业务需要添加日志组件的相关插件。

首先安装并运行Elasticsearch(es) 和 Kibana

这里不详细讲 es/kibana 的配置,安装好jdk以后 直接运行bin目录下的elasticsearch.bat/kibana.bat 就可以了

注意 :
1.es 运行依赖jdk
2.Kibana 运行需要 对应es 对应的版本

其次扩展已有日志组件使其通过es支持日志收集

由于项目中我采用的时Serilog所以下面的代码都是以Serilog为主,但由于是实现Asp.Net Core中的ILogger,使用实际差距不大

1.根据需要安装依赖组件

必须(二选一)

  • Serilog Serilog 基本库
  • Serilog.AspNetCore AspNetCore框架整合库,包含Serlog基本库和控制台日志实现

可选

  • Serilog.Extensions.Logging 包含了注入Serilog的扩展方法
  • Serilog.Sinks.Async 实现了日志异步收集
  • Serilog.Sinks.Console 实现了控制台日志
  • Serilog.Settings.Configuration 如果需要通过json配置文件配置Serilog的话需要安装此库
  • Serilog.Sinks.Elasticsearch 实现了Elasticsearch收集

2.初始化Serilog,并添加至AspNetCore的ILoggerFactory

这里要添加serilog的方式有几种,常用的是通过硬编码的情况,另外是通过 xml,json等配置文件的方式,这里都做一个简单的示例,更详细的配置信息可以查看Serilog.Sinks github仓库中的介绍,非常详细,这里不做过多介绍
Serilog.Settings.Configuration项目地址

1.硬编码的方式


using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ForDotNet.Common.Consul.Extensions;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Sinks.Elasticsearch;

namespace ForDotNet.Web.Api
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;

            //初始化Serilog
            Log.Logger = new LoggerConfiguration()
                    .Enrich.FromLogContext()
                    .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level}] {SourceContext}{NewLine}{Message:lj}{NewLine}{Exception}{NewLine}")
                    .WriteTo.Elasticsearch(new ElasticsearchSinkOptions(new Uri("http://localhost:9200"))
                    {
                        AutoRegisterTemplate = true,
                        IndexFormat = "Api1-{0:yyyy-MM-dd}",// es index模板
                    })
                    .CreateLogger();
        }

        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)
        {
            // 添加当前项目服务发现
            services.AddConsulServiceDiscovery();

            services.AddControllers();
        }

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

            // 添加serilog
            loggerFactory.AddSerilog();

            app.UseConsulServiceDiscovery(life);

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}


2.通过配置文件的方式

准备需要配置的信息,这里我们使用的是appsettings.json文件


{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "ServiceOptions": {
    "ServiceIP": "localhost",
    "ServiceName": "Auth",
    "Port": 5800,
    "HealthCheckUrl": "/api/health",
    "ConsulOptions": {
      "Scheme": "http",
      "ConsulIP": "localhost",
      "Port": 8500
    }
  },
  "Serilog": {
    "WriteTo": [
      {
        "Name": "Elasticsearch",
        "Args": {
          "nodeUris": "http://localhost:9200;http://remotehost:9200/",
          "indexFormat": "auth-{0:yyyy-MM-dd}",
          "autoRegisterTemplate": true
        }
      }
    ]
  }
}

然后更改Serilog的相关初始化代码为


public Startup(IConfiguration configuration,IHostEnvironment hostEnvironment)
        {

           // 读取配置文件
           var builder = new ConfigurationBuilder()
               .SetBasePath(hostEnvironment.ContentRootPath)
               .AddJsonFile("appsettings.json", true, true)
               .AddJsonFile($"appsettings.{hostEnvironment.EnvironmentName}.json", true, true)
               .AddEnvironmentVariables();

            Configuration = builder.Build();

            Log.Logger = new LoggerConfiguration()
                    .ReadFrom.Configuration(Configuration)
                    .CreateLogger();
        }

3.将日志记录操作转为异步

由于serilog.sinks实现大多都是同步的方式实现,所以如果需要以异步的方式收集日志的话需要引用Serilog.Sinks.Async这个库,并更改相关代码。详细请见Serilog.Sinks.Async官方仓库,
同样,异步的方式也可以通过配置文件实现,可以查看官方仓库,这里只使用硬编码的方式。


public Startup(IConfiguration configuration,IHostEnvironment hostEnvironment)
        {

           // 读取配置文件
           var builder = new ConfigurationBuilder()
               .SetBasePath(hostEnvironment.ContentRootPath)
               .AddJsonFile("appsettings.json", true, true)
               .AddJsonFile($"appsettings.{hostEnvironment.EnvironmentName}.json", true, true)
               .AddEnvironmentVariables();

            Configuration = builder.Build();

            Log.Logger = new LoggerConfiguration()
                    .WriteTo.Async(configure =>
                    {
                        configure
                        .Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level}] {SourceContext}{NewLine}{Message:lj}{NewLine}{Exception}{NewLine}", theme: AnsiConsoleTheme.Code);

                        configure
                        .Elasticsearch(new ElasticsearchSinkOptions(new Uri("http://localhost:9200"))
                        {
                            AutoRegisterTemplate = true,
                            IndexFormat = "auth-{0:yyyy-MM-dd}",

                        });
                    })
                    .CreateLogger();
        }

3.运行并查看

启动Elasticserach,Kibana,项目后

查看控制台,发现同样的日志输出了两遍,这是因为AspNetCore默认实现的LoggerProvider 没有清除所以会导致 打印输出,我们在启动时清除默认Provider即可

清除LoggerProvider

然后运行并查看日志,是不是清爽了很多

然后我们访问Kiabana查看我们刚刚收集的日志

访问 http://localhost:5601 Kibana默认项目地址,不同Kibana版本页面会有差异

点击Management建立我们的日志收集模型

这里由于我已经建立过其他的模块的信息,所以可以看到我已经创建的信息,这里我们点击创建新的信息

这里需要输入 正则表达式 匹配收集的信息,这里我们输入我们定义的模板开头的api1并点击下一步

这里选择@timestamp作为索引模式,也可以选择不添加,然后创建

创建完成后 去到 Discover 模块

在左边选择需要查看的index

就可以看到我们的日志已经收集到es中了,可以通过kibana查看了

如果觉得字段过于复杂的话 可以在左边选择过滤的字段查看 我这里已经只选择了 leve 和 message

好了 ,以上我就我分享的 建立分布式日志的内容了,如果有纰漏及错误 希望大家指出,谢谢

原文地址:https://www.cnblogs.com/ablewang/p/13170391.html