首页 > Web开发 > 详细

asp.net core 日志记录到elk

时间:2019-08-14 12:51:26      阅读:172      评论:0      收藏:0      [点我收藏+]

关于ELK的安装大家可以参考ubuntu18 docker中部署ELK 和 caas/docker-elk ,

首先需要在ELK中创建一个index patterns

技术分享图片技术分享图片?

首先我们创建一个aspnetcore webapi项目

1.添加如下引用:

Serilog
Serilog.Sinks.ElasticSearch
Serilog.Extensions.Logging
技术分享图片

2.修改appsettings.json文件:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "System": "Information",
      "Microsoft": "Information"
    }
  },
  "AllowedHosts": "*",
  "ElasticConfiguration": {
    "Uri": "http://192.168.100.5:5000/"
  }
}

3.修改Startup.cs文件

  public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
             var elasticUri = Configuration["ElasticConfiguration:Uri"];
            Log.Logger = new LoggerConfiguration().Enrich.FromLogContext().MinimumLevel.Debug() .WriteTo.Elasticsearch(
                new ElasticsearchSinkOptions(new Uri(elasticUri)) { MinimumLogEventLevel=LogEventLevel.Information,AutoRegisterTemplate=true,  })
                .CreateLogger();
        }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddLogging(loggingBuilder => loggingBuilder.AddSerilog(dispose: true));
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }

4.修改controller:

 ILogger<ValuesController> _logger;
        public ValuesController(ILogger<ValuesController> logger) {
            _logger = logger;
        }

        [HttpGet]
        public ActionResult<IEnumerable<string>> Get()
        {
            _logger.LogInformation($"oh hai there! : {DateTime.UtcNow}");
            try
            {
                throw new Exception("oops. i haz cause error in UR codez.");
            }
            catch (Exception ex)
            {
                _logger.LogCritical("ur app haz critical error", ex);
                _logger.LogError(ex, "ur code iz buggy.");
            }
            return new string[] { "value1", "value2" };
        }

5.运行项目然后在elk中验证

技术分享图片

技术分享图片

备注:网上关于elk的地址都是http://xxx:9200 (elasticsearch地址), 我在测试的时候发现怎么都没有写入到elk,后来改为5000(Logstash的地址)就好了

技术分享图片技术分享图片?

参考:

Logging with ElasticSearch, Kibana, ASP.NET Core and Docker

thecarlo/elastic-kibana-netcore-serilog

asp.net core 日志记录到elk

原文:https://www.cnblogs.com/majiang/p/11351156.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!