前言
一直以来对于.NETCore微服务相关的技术栈都处于一个浅尝辄止的了解阶段,在现实工作中也对于微服务也一直没有使用的业务环境,所以一直也没有整合过一个完整的基于.NETCore技术栈的微服务项目。正好由于最近刚好辞职,有了时间可以写写自己感兴趣的东西,所以在此想把自己了解的微服务相关的概念和技术框架使用实现记录在一个完整的工程中,由于本人技术有限,所以错误的地方希望大家指出。
目录
为什么需要分布式日志
在项目的运行运行过程中,不可避免的是由于系统原因或者业务原因产生的警告或异常,这时我们需要根据产生的异常或警告信息快速排查出现的问题并修复,但是由于多个服务产生的过于庞杂的信息使那些以往通过直接写入日志文件的方式已经无法满足快速排查的需求了,因为直接写入日志文件只能根据事先制定好的规则查看日志信息,但是由于体量过大导致排查起来异常麻烦,例如,如果问题出现在 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.硬编码的方式
1using System; 2using System.Collections.Generic; 3using System.Linq; 4using System.Threading.Tasks; 5using ForDotNet.Common.Consul.Extensions; 6using Microsoft.AspNetCore.Builder; 7using Microsoft.AspNetCore.Hosting; 8using Microsoft.AspNetCore.HttpsPolicy; 9using Microsoft.AspNetCore.Mvc; 10using Microsoft.Extensions.Configuration; 11using Microsoft.Extensions.DependencyInjection; 12using Microsoft.Extensions.Hosting; 13using Microsoft.Extensions.Logging; 14using Serilog; 15using Serilog.Sinks.Elasticsearch; 16 17namespace ForDotNet.Web.Api 18{ 19 public class Startup 20 { 21 public Startup(IConfiguration configuration) 22 { 23 Configuration = configuration; 24 25 //初始化Serilog 26 Log.Logger = new LoggerConfiguration() 27 .Enrich.FromLogContext() 28 .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level}] {SourceContext}{NewLine}{Message:lj}{NewLine}{Exception}{NewLine}") 29 .WriteTo.Elasticsearch(new ElasticsearchSinkOptions(new Uri("http://localhost:9200")) 30 { 31 AutoRegisterTemplate = true, 32 IndexFormat = "Api1-{0:yyyy-MM-dd}",// es index模板 33 }) 34 .CreateLogger(); 35 } 36 37 public IConfiguration Configuration { get; } 38 39 // This method gets called by the runtime. Use this method to add services to the container. 40 public void ConfigureServices(IServiceCollection services) 41 { 42 // 添加当前项目服务发现 43 services.AddConsulServiceDiscovery(); 44 45 services.AddControllers(); 46 } 47 48 // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 49 public void Configure(IApplicationBuilder app, IWebHostEnvironment env,ILoggerFactory loggerFactory,IHostApplicationLifetime life) 50 { 51 if (env.IsDevelopment()) 52 { 53 app.UseDeveloperExceptionPage(); 54 } 55 56 // 添加serilog 57 loggerFactory.AddSerilog(); 58 59 app.UseConsulServiceDiscovery(life); 60 61 app.UseHttpsRedirection(); 62 63 app.UseRouting(); 64 65 app.UseAuthorization(); 66 67 app.UseEndpoints(endpoints => 68 { 69 endpoints.MapControllers(); 70 }); 71 } 72 } 73} 74 75
2.通过配置文件的方式
准备需要配置的信息,这里我们使用的是appsettings.json文件
1{ 2 "Logging": { 3 "LogLevel": { 4 "Default": "Information", 5 "Microsoft": "Warning", 6 "Microsoft.Hosting.Lifetime": "Information" 7 } 8 }, 9 "ServiceOptions": { 10 "ServiceIP": "localhost", 11 "ServiceName": "Auth", 12 "Port": 5800, 13 "HealthCheckUrl": "/api/health", 14 "ConsulOptions": { 15 "Scheme": "http", 16 "ConsulIP": "localhost", 17 "Port": 8500 18 } 19 }, 20 "Serilog": { 21 "WriteTo": [ 22 { 23 "Name": "Elasticsearch", 24 "Args": { 25 "nodeUris": "http://localhost:9200;http://remotehost:9200/", 26 "indexFormat": "auth-{0:yyyy-MM-dd}", 27 "autoRegisterTemplate": true 28 } 29 } 30 ] 31 } 32} 33
然后更改Serilog的相关初始化代码为
1public Startup(IConfiguration configuration,IHostEnvironment hostEnvironment) 2 { 3 4 // 读取配置文件 5 var builder = new ConfigurationBuilder() 6 .SetBasePath(hostEnvironment.ContentRootPath) 7 .AddJsonFile("appsettings.json", true, true) 8 .AddJsonFile($"appsettings.{hostEnvironment.EnvironmentName}.json", true, true) 9 .AddEnvironmentVariables(); 10 11 Configuration = builder.Build(); 12 13 Log.Logger = new LoggerConfiguration() 14 .ReadFrom.Configuration(Configuration) 15 .CreateLogger(); 16 } 17
3.将日志记录操作转为异步
由于serilog.sinks实现大多都是同步的方式实现,所以如果需要以异步的方式收集日志的话需要引用Serilog.Sinks.Async这个库,并更改相关代码。详细请见Serilog.Sinks.Async官方仓库,
同样,异步的方式也可以通过配置文件实现,可以查看官方仓库,这里只使用硬编码的方式。
1public Startup(IConfiguration configuration,IHostEnvironment hostEnvironment) 2 { 3 4 // 读取配置文件 5 var builder = new ConfigurationBuilder() 6 .SetBasePath(hostEnvironment.ContentRootPath) 7 .AddJsonFile("appsettings.json", true, true) 8 .AddJsonFile($"appsettings.{hostEnvironment.EnvironmentName}.json", true, true) 9 .AddEnvironmentVariables(); 10 11 Configuration = builder.Build(); 12 13 Log.Logger = new LoggerConfiguration() 14 .WriteTo.Async(configure => 15 { 16 configure 17 .Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level}] {SourceContext}{NewLine}{Message:lj}{NewLine}{Exception}{NewLine}", theme: AnsiConsoleTheme.Code); 18 19 configure 20 .Elasticsearch(new ElasticsearchSinkOptions(new Uri("http://localhost:9200")) 21 { 22 AutoRegisterTemplate = true, 23 IndexFormat = "auth-{0:yyyy-MM-dd}", 24 25 }); 26 }) 27 .CreateLogger(); 28 } 29
3.运行并查看
启动Elasticserach,Kibana,项目后
查看控制台,发现同样的日志输出了两遍,这是因为AspNetCore默认实现的LoggerProvider 没有清除所以会导致 打印输出,我们在启动时清除默认Provider即可

清除LoggerProvider

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

然后我们访问Kiabana查看我们刚刚收集的日志
访问 http://localhost:5601 Kibana默认项目地址,不同Kibana版本页面会有差异

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

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

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

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

创建完成后 去到 Discover 模块

在左边选择需要查看的index

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

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

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