• 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

  • 相关阅读:
    VS2010+WPF+LINQ for MySQL
    WPF项目中解决ConfigurationManager不能用(转)
    DBLinq (MySQL exactly) Linq To MySql(转)
    循环左移实现
    C166 -MDH
    C166 8位字节位运算赋值-代码优化
    c166 -div
    js实现类似新闻条目人物简介不间断的滚动
    js实现新闻条目滚动效果
    php写杨辉三角算法
  • 原文地址:https://www.cnblogs.com/majiang/p/11351156.html
Copyright © 2020-2023  润新知