asp.net core 日志记录到elk

关于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

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值