How to handle Serilog.Sinks.Elasticsearch on long waiting when it faces Elastic connection failed?

Viewed 596

I use Serilog to persist logs and also use Serilog.Sinks.Elasticsearch to store logs in Elastic search. everything works fine but the problem is when the ElasticSearch connection is failed the log routine does not behave correctly and takes a lot of time without any action or exceptions! I can not let logs change the application routine(make a long time waiting). What can I do for this purpose and what is the best practice?

This is My code (when ES connection is failed it takes a lot of time in logger.XXXX)

        static void Main(string[] args)
    {

        using (var logger = BuildSerilog())
        {

            logger.Information("Start");

            for (int i = 0; i < 1500000; i++)
            {
                if (new Random().Next(2, 4) == 3)
                {
                    logger.Information("Some Error");

                }
                try
                {

                    logger.Information("It's logging to the console but not in the file.{0}", i);
                }
                catch (Exception ex)
                {
                    logger.Information(ex, "Application crashed");
                }
                logger.Information("Start");

            }
        }
        Log.CloseAndFlush();


    }




 private static Logger BuildSerilog()
    {
        var logger = new LoggerConfiguration()
                        .MinimumLevel.Debug()
                        .WriteTo.Console()
                        .WriteTo.File("D:/Home/TestApp/testDoc.txt", outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} \\[{Level:u3}\\] {Message:lj}{Properties}{NewLine}{Exception}")
                        .WriteTo.Elasticsearch(new ElasticsearchSinkOptions(
                         new Uri("http://localhost:9200/"))
                        {
                            
                            AutoRegisterTemplate = true,
                                AutoRegisterTemplateVersion = AutoRegisterTemplateVersion.ESv7,
                                IndexFormat = "test-index-{0:yyyy.MM.dd}",
                                EmitEventFailure =  EmitEventFailureHandling.ThrowException,
                            FailureCallback = e => Console.WriteLine("Unable to submit event " + e.MessageTemplate),

                            DeadLetterIndexName = "test-deadletter-{0:yyyy.MM.dd}"
                            })
                        .CreateLogger();

        Log.Logger = logger;

        return logger;
    }
0 Answers
Related