• 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

  • 相关阅读:
    HashMap和Hashtable的区别
    java倒计时三种简单实现方式
    AngularJS---基本操作
    AngularJS---认识AngularJS
    Java线程面试题
    JAVA中高访问量高并发的问题怎么解决?
    Java高并发,如何解决,什么方式解决
    Map总结
    Github
    反射
  • 原文地址:https://www.cnblogs.com/majiang/p/11351156.html
Copyright © 2020-2023  润新知