代码改变世界

Serilog日志存储到ES数据库(存储到具体索引)

2020-12-15 14:20  石吴玉  阅读(674)  评论(0编辑  收藏  举报

1..net core3.1项目

 

2.配置文件

  "Serilog": {
    "ApplicationName": "xx.xxx.xx", //可选参数
    "MinimumLevel": {
      "Default": "Debug", //手写日志的层级
      //在 Override 当中设定一些 中间件的记录日志层级(默认情况下,serilog经过每个中间件都会记录日志)
      "Override": {
        //在此配置一些方法被调用时的日志等级,等级有:Verbose、Debug、Information、Warning、Error、Fatal
        "Microsoft": "Warning",
        "System": "Warning",
        "Microsoft.AspNetCore": "Warning",
        "Microsoft.Hosting.Lifetime": "Warning",
        "Microsoft.AspNetCore.Hosting.Diagnostics": "Warning"
      }
    }
  },
  //ES数据库的配置
  "LogToElasticSearch": {
    "Enabled": "true",
    "ElasticSearch": {
      "Url": "http://es.xxxx.xxxx.cn",//数据库地址
      "IndexFormat": "xxx.xxxxxx.dev-{0:yyyy.MM.dd}",//当前程序录入日志的索引名(类似mysql的表)
      "UserName": "xx",//登录名
      "Password": "xxxxx"//密码
    }
  }
View Code

 

3.serilogHelp初始化配置

   public static class SerilogCreatorExtensions
    {

        public static Serilog.Core.Logger CreateSerilog(
            this IConfigurationRoot configuration,
            IWebHostEnvironment env)
        {
            return BuildSerilogConfiguration(configuration, env).CreateLogger();
        }

        private static LoggerConfiguration BuildSerilogConfiguration(
            IConfiguration configuration,
            IWebHostEnvironment env)
        {
            // 默认读取 configuration 中 "Serilog" 节点下的配置
            var loggerConfiguration = new LoggerConfiguration();
            SetSerilogConfiguration(loggerConfiguration, configuration, env);
            return loggerConfiguration;
        }

        public static void SetSerilogConfiguration(
            LoggerConfiguration loggerConfiguration,
            IConfiguration configuration,
            IWebHostEnvironment env)
        {
            // 默认读取 configuration 中 "Serilog" 节点下的配置
            loggerConfiguration.ReadFrom.Configuration(configuration)
                .Enrich.WithExceptionDetails()
                .Enrich.WithExceptionDetails(new DestructuringOptionsBuilder()
                    .WithDefaultDestructurers()
                    .WithDestructurers(new[] { new DbUpdateExceptionDestructurer() })
                )
                .Enrich.FromLogContext()
                .WriteTo.Console();

            // 调试模式输出至本地文件 
            if (env.IsDevelopment())
            {
                loggerConfiguration
                    .WriteTo.File("App_Data/logs/logs.txt", rollingInterval: RollingInterval.Day);
            }

            var writeToElasticSearch = configuration.GetValue("LogToElasticSearch:Enabled", false);

            // LogToElasticSearch:Enabled = true 才输出至ES
            if (!writeToElasticSearch)
                return;

            var applicationName = configuration["Serilog:ApplicationName"].ToLower();

            // 需要设置LogToElasticSearch ApplicationName
            if (string.IsNullOrEmpty(applicationName))
                return;

            var esUrl = configuration["LogToElasticSearch:ElasticSearch:Url"];
            // 需要设置ES URL
            if (string.IsNullOrEmpty(esUrl))
                return;

            //var indexFormat = applicationName + "-{0:yyyy.MM.dd}";

            var indexFormat = configuration["LogToElasticSearch:ElasticSearch:IndexFormat"];
            // 需要设置ES URL
            if (string.IsNullOrEmpty(indexFormat))
                return;

            var esUserName = configuration["LogToElasticSearch:ElasticSearch:UserName"];
            var esPassword = configuration["LogToElasticSearch:ElasticSearch:Password"];

            loggerConfiguration.Enrich.WithProperty("Application", applicationName);

            loggerConfiguration.WriteTo.Elasticsearch(BuildElasticSearchSinkOptions(esUrl, indexFormat, esUserName, esPassword));
        }

        // 创建Es连接
        private static ElasticsearchSinkOptions BuildElasticSearchSinkOptions(
            string url,
            string indexFormat,
            string userName,
            string password)
        {
            if (string.IsNullOrEmpty(userName))
            {
                return new ElasticsearchSinkOptions(new Uri(url))
                {
                    AutoRegisterTemplate = true,
                    AutoRegisterTemplateVersion = AutoRegisterTemplateVersion.ESv6,
                    IndexFormat = indexFormat
                };
            }

            return new ElasticsearchSinkOptions(new Uri(url))
            {
                AutoRegisterTemplate = true,
                AutoRegisterTemplateVersion = AutoRegisterTemplateVersion.ESv6,
                IndexFormat = indexFormat,
                ModifyConnectionSettings = x => x.BasicAuthentication(userName, password)
            };
        }
    }
View Code

 

4.在Program.cs文件中注入 Serilog服务

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

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder => {
                webBuilder.UseStartup<Startup>();
                webBuilder.UseSerilog((context, loggerConfiguration) =>
                {
                    SerilogCreatorExtensions.SetSerilogConfiguration(
                        loggerConfiguration,
                        context.Configuration,
                        context.HostingEnvironment);
                });
            });
    }
View Code

 

6.在方法中调用

    public class Test
    {
        private ILogger _log;
        public Test(ILogger log)
        {
            _log = log;
        }

        public string WriteLog()
        {
            _log.Information("日志");
            return "日志";
        }
    }
View Code