关于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的地址)就好了
参考: