在 ASP.NET Web API 中使用 Serilog 登录 ElasticSearch

Logging into ElasticSearch with Serilog in ASP.NET Web API

我正在尝试使用 Serilog 在我的 ASP.NET Web API 项目之一中登录 Elasticsearch,但不幸的是,我在 Kibana 中找不到日志。

public class Logger
{
    private readonly ILogger _localLogger;

    public Logger()
    {
        ElasticsearchSinkOptions options = new ElasticsearchSinkOptions(new Uri("xxx"))
        {
            IndexFormat = "log-myservice-dev",
            AutoRegisterTemplate = true,
            ModifyConnectionSettings = (c) => c.BasicAuthentication("yyy", "zzz"),
            NumberOfShards = 2,
            NumberOfReplicas = 0
        };

        _localLogger = new LoggerConfiguration()
                            .MinimumLevel.Information()
                            .WriteTo.File(HttpContext.Current.Server.MapPath("~/logs/log-.txt"), rollingInterval: RollingInterval.Day)
                            .WriteTo.Elasticsearch(options)
                            .CreateLogger();
    }

    public void LogError(string error)
    {
        _localLogger.Error(error);
    }

    public void LogInformation(string information)
    {
        _localLogger.Information(information);
    }
}

我可以在上面指定的文件中看到日志,只是在 Elasticsearch 中看不到。所以,我想知道有什么方法可以调试它无法登录 Elasticsearch 的原因吗?我也愿意使用其他日志记录框架登录 Elasticsearch。

*Elasticsearch 的凭据和 url 有效,因为我已经在我的其他 AWS Lambda 项目(.net 核心)中实现了它。

要查看到底出了什么问题,最简单的方法是写入控制台,如果是 ASP.NET 项目,它将是 Debug.WriteLine。所以查看出了什么问题的代码是

Serilog.Debugging.SelfLog.Enable(msg => Debug.WriteLine(msg));

ElasticsearchSinkOptions options = new ElasticsearchSinkOptions(new Uri("xxx"))
{
         IndexFormat = "log-myservice-dev",
         AutoRegisterTemplate = true,
         ModifyConnectionSettings = (c) => c.BasicAuthentication("yyy", "zzz"),
         NumberOfShards = 2,
         NumberOfReplicas = 1,
         EmitEventFailure = EmitEventFailureHandling.WriteToSelfLog,
         MinimumLogEventLevel = Serilog.Events.LogEventLevel.Information
};

从输出控制台检索到以下错误消息。

Failed to create the template. Elasticsearch.Net.ElasticsearchClientException: The request was aborted: Could not create SSL/TLS secure channel.. Call: Status code unknown from: HEAD /_template/serilog-events-template ---> System.Net.WebException: The request was aborted: Could not create SSL/TLS secure channel.

问题很明确。在我的记录器中添加了以下内容 class 构造函数帮助解决了这个问题。

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

希望它能帮助其他在尝试使用 Serilog 登录 Elasticsearch for .Net Framework 时遇到问题的人。