目录

 

前言 

创建.NETCORE 3.1应用程序 

在Kibana中查看 

稍微拓展一下 


前言 

之前在本地搭建好了Elasticsearch,现在考虑使用最简单的方式将应用程序的日志信息写入其中。测试的程序使用的是 .NETCORE 3.1,利用Serilog组件快速写入一些日志。这篇文档唯一的目标就是快速实现,之后的文章在做分析和讲解。 

创建.NETCORE 3.1应用程序 

  1. 利用Visual Studio 2019快速创建一个.Netcore 3.1的应用程序 

1. 使用Nuget包管理工具安装以下Package 

    <PackageReference Include="Serilog.AspNetCore" Version="4.1.0" /> 
    <PackageReference Include="Serilog.Extensions.Logging" Version="3.0.1" /> 
    <PackageReference Include="Serilog.Sinks.Elasticsearch" Version="8.4.1" /> 

 

2. 修改Program.cs文件,这里一切从简,目标就是快速写入一些日志到ES中。关于Serilog不在展开 

using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Serilog;
using Serilog.Sinks.Elasticsearch;
using System;

namespace Demo.ElasticSearchLog
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .UseSerilog((ctx, config) =>
                {
                    config
                        .MinimumLevel.Debug()
                        .Enrich.FromLogContext()
                        .WriteTo.Elasticsearch(new ElasticsearchSinkOptions(new Uri("https://localhost:9200"))
                        {
                            IndexFormat = "logstash-{0:yyyy.MM}",
                            EmitEventFailure = EmitEventFailureHandling.RaiseCallback,
                            FailureCallback = e => Console.WriteLine("Unable to submit event " + e.MessageTemplate),
                            AutoRegisterTemplate = true,
                            AutoRegisterTemplateVersion = AutoRegisterTemplateVersion.ESv7,
                            ModifyConnectionSettings =
                                conn =>
                                {
                                    conn.ServerCertificateValidationCallback((source, certificate, chain, sslPolicyErrors) => true);
                                    conn.BasicAuthentication("elastic", "U3G44HpMwQv3Y5tq916TyV74");

                                    return conn;
                                }
                        })
                        .WriteTo.Console();
                })
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }
}
  • 设置MinimumLevel为Debug 

  • Entich.FromLogContext 这里的作用将一些环境信息写入日志中 

  • new ElasticsearchSinkOptions设置了ES的地址,之前我们运行的本地的K8S中 

  • IndexFormat 默认是到天(logstash-{0:yyyy.MM.dd}),我修改成到月。不同IndexFormat的日志会存储在不同索引中 

  • EmitEventFailure 设置了当失败时调用FailureCallback 

  • ConnextionSettings这里需要设置了2个地方,一个时忽略证书(之前没有配置一个有效的证书),一个是设置了 BasicAuthentioncation。如果是按照我之前的文件配置的环境,这里只需要修改password为你的就可以了 

3. 修改Startup.cs文件,增加一个我们自己的日志。输出了一个"Hello Elasticsearch." 

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Sinks.Elasticsearch;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Demo.ElasticSearchLog
{
    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
        }

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

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapGet("/", async context =>
                {
                    logger.LogInformation("Hello Elasticsearch.");
                    await context.Response.WriteAsync("Hello World!");
                });
            });
        }
    }
}

4. 运行代码,可以发送了一个PUT请求到ES中,这里是创建一个Index Template 

 

在Kibana中查看 

1. 打开Kibana(https://localhost:5601/),我们需要先创建Index patterns才可以方便查看。首先在首页选择Manage。 

 

2. 选择Index Management可以看到根据我们之前应用中设置的 IndexFormat 生成的Name 。这里只是看一下数据,如果不存在就需要考虑应用是否异常了。我之前遇到过密码不对、证书等问题。 

 

3. 选择Index patterns选项卡,点击Create Index patterns 

 

4. 我输入了logstash-*作为 Index pattern name,目前由于我只有5月的数据,所以只匹配到了一个source。当然也可以不使用带通配符的名称。点击Nex step按钮。 

 

5. Time fieId选择了@timestamp,然后选择Create index pattern按钮。 

 

6. 选择Kibana左侧菜单(不是刚才manage的左侧菜单)中的Discover,并且选择刚才我们创建了logstash-*。 

7. 可以在右侧看到我们刚才写入的日志信息了,我添加了RequestPath和Message到Selected Fieldes中。 

稍微拓展一下 

这里先大致了解一下刚才运行的状况下有哪些名词,不展开细讲。 

1. Index 

索引是文档(Document)的容器,是一类文档的集合。可以大致理解等同于关系型数据库的表。 

2. Document  

Index 里面单条的记录称为Document(文档)。可以大致理解等同于关系型数据库表中的行。 也可以通过Restful API去查看。

3. index template 

Index template包含了settings和mappings信息。刚才我们可以从VS2019的Event窗口中看到,通过httpclient发送了一个PUT请求到 localhost:9200 端口(PUT https://localhost:9200/_template/serilog-events-template ),这里只有在第一次运行时会看到。 

通过GET的方式我们可以获取到它 

4. Index patterns 

要在Kibana中可视化和浏览数据,必须创建Index patterns。 

5. Dev Tools 

刚才我的一些操作都是用POST MAN,也可以使用Dev Tools来更方便的完成。 

上一篇 使用ELK搭建日志平台(一):本地安装Elasticsearch 和 Kibana

下一篇 使用ELK搭建日志平台(三):Opentracing链路追踪

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐