SlackLogger icon indicating copy to clipboard operation
SlackLogger copied to clipboard

No logs sent to Slack in console application

Open yaroslav-metelev opened this issue 2 years ago • 1 comments

Console application may end before sent any logs. Sample code:

    internal class Program
    {
        static async Task Main(string[] args)
        {
            IConfiguration configuration =
                new ConfigurationBuilder()
                    .Build();

            var serviceProvider = new ServiceCollection()
                  .AddSingleton(configuration)
                  .AddLogging(builder =>
                  {
                      builder.AddConsole();
                      builder.AddSlack(options =>
                      {
                          options.WebhookUrl =
                        "https://hooks.slack.com/services/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";
                          options.LogLevel = LogLevel.Information;
                      });
                  }).BuildServiceProvider();


            var logger = serviceProvider.GetService<ILogger<Program>>();

            logger.LogError("Log 1");
            logger.LogError("Log 2");
            logger.LogError("Log 3");

            // await Task.Delay(1000); // no logs is sent to Slack without delay before end application
        }
    }

This code send no logs into Slack unless I uncomment the line await Task.Delay(1000); in the end. In the same time all logs are displayed correctly in console even without await Task.Delay(1000); line.

Logging in Slack should work without await Task.Delay(1000);

yaroslav-metelev avatar May 23 '22 04:05 yaroslav-metelev

Thanks for reporting - this is not the desired behaviour indeed.

The reason this happens is that http calls to Slack er sent in a fire-and-forget fashion (https://github.com/severisv/SlackLogger/blob/c46b8f59e70f303afc748d16ed048b2c10ab1961/SlackLogger/SlackService.cs#L26), which is important so that the logger doesn't delay the flow of the application.

Maybe there are solutions to this while still implementing it as an ILogger - I'm happy to receive suggestions or pull requests ☺️

severisv avatar May 23 '22 08:05 severisv