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

Yta*_*tan 1 elasticsearch asp.net-web-api serilog

我正在尝试使用 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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

*Elasticsearch 的凭证和 URL 有效,因为我已在其他 AWS Lambda 项目 (.net core) 中实现了此功能。

Yta*_*tan 5

要准确查看出了什么问题,最简单的方法是写入控制台,对于 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
};
Run Code Online (Sandbox Code Playgroud)

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

创建模板失败。Elasticsearch.Net.ElasticsearchClientException:请求已中止:无法创建 SSL/TLS 安全通道..调用:状态代码未知来自:HEAD /_template/serilog-events-template ---> System.Net.WebException:请求是已中止:无法创建 SSL/TLS 安全通道。

这个问题已经很明确了。在我的记录器类构造函数中添加以下内容有助于解决此问题。

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
Run Code Online (Sandbox Code Playgroud)

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