【问题标题】:Serilog not working with ElasticsearchSerilog 不适用于 Elasticsearch
【发布时间】:2017-08-23 13:40:49
【问题描述】:

我已经在我的 Windows 7 机器上本地安装了 Elasticsearch。它工作正常,我可以使用邮递员查询它。使用 Postman,我还创建了一个名为 cmstest 的索引。这有一个名为 zdsf 的表。如果我得到这个索引的映射 (http://localhost:9200/cmstest/_mapping),我会得到以下信息:

我也可以使用 Postman 将条目发布到此表。

现在,我正在尝试使用我的 .NET 4.5 应用程序中的 Serilog 来登录到 Elasticsearch 的这个 localhost 实例。但似乎没有任何效果。这是我的代码:

var elasticUri = new Uri("http://localhost:9200/cmstest/zdsf");

var loggerConfig = new LoggerConfiguration()
                .WriteTo.Elasticsearch(new ElasticsearchSinkOptions(elasticUri)
                {
                    AutoRegisterTemplate = true
                });

zdsf z = new zdsf();

z.filedate = DateTime.Now;
z.filename = "File2";

var logger = loggerConfig.CreateLogger();

var jsonString = new JavaScriptSerializer().Serialize(z);

logger.Error(jsonString);

我已尝试使用以下网址:

http://localhost:9200/

http://localhost:9200/cmstest

http://localhost:9200/cmstest/zdsf

我尝试将 AutoRegisterTemplate 设置为 true 和 false。但是 Serilog 似乎没有向 elasticsearch 写入任何内容。它甚至没有给出例外。它只是完成而没有记录任何内容。

另一个有趣的事情是,当 serilog 应该进行日志记录时,fiddler 没有显示到 http://localhost:9200 的任何流量。但是当我通过邮递员发出请求时,它会显示流量。

我做错了什么?如何让 Serilog 工作?

更新 1:更新了 ElasticSearch.Net nuget 包

我发现 Sink 使用的是旧版本的 ElasticSearch.Net。所以,我删除了 ElasticSearch.Net nuget 包并下载了最新的。这还在我的 app.config 中添加了所需的 BindingRedirects。但是登录到 ElasticSearch 仍然不起作用。

【问题讨论】:

  • 您需要查看 ElasticsearchSinkOptions 上的 IndexFormat 参数。 Url 不会包含索引,而是 Elasticsearch 实例的 url。

标签: .net elasticsearch logging elastic-stack serilog


【解决方案1】:

在我的案例中出现了多个问题:

  1. 当我尝试使用控制台应用程序时,该应用程序在写入日志之前被终止。这可以通过在应用终止之前使用 Console.Readline() 或 Log.CloseAndFlush() 语句来解决。
  2. 接下来,Serilog.Sinks.Elasticsearch 包依赖于旧版本的 Elasticsearch.net nuget 包。要达到 Elastic 5.X,您需要更高版本的 Elasticsearch.net 包。于是,我手动删除了这个包,得到了最新版本。
  3. 现在,即使我拥有最新的 Elasticsearch.net 包,某些地方的某些代码仍在寻找旧包。添加程序集重定向解决了这个问题。
  4. 接下来,我了解到 Serilog.Sinks.Elasticsearch 具有最低日志记录级别。我将其设置为详细。但这没有用。问题是我将它设置在 Sink 而不是 Serilog 级别。在此之后,我能够让我的本地应用程序正常工作。
  5. 我认为这在 Azure Function(在这种情况下是我想要的应用程序)中仍然不起作用,因为 Azure Function 似乎没有程序集重定向。为此,我下载了 Serilog.Sinks.Elasticsearch 源代码,删除了对旧版本 Elasticsearch.net 的引用,并将其指向最新版本。我计划使用此代码而不是 nuget 包。

【讨论】:

  • 谢谢。 1 和/或 2 为我修复了它。
【解决方案2】:

你读过Lifecycle of Loggers吗?您必须调用 Log.CloseAndFlush()(如果您通过全局 Log 对象登录),或处置本地 Logger 对象。否则,您的日志事件永远不会被写入。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多