Search code examples
asp.net-coreserilog

How use Serilog email with asp.net core 2.1


In my asp.net core 2.1 project want send mail on error event. I have an error controller that catch global error and log them with ILogger

Now in main method of Program.cs i do what documentation suggest but mail is not sent! Sink works if i move code in ErrorController but i think is bad way

public static void Main(string[] args)
    {
         var emailInfo = new EmailConnectionInfo
         {
             FromEmail = "xxx",
             ToEmail = "xxxx;",
             MailServer = "smtp.gmail.com",
             EmailSubject = "Error "
        };

         using (var logger = new LoggerConfiguration()
                 .MinimumLevel.Error()
                 .WriteTo.Email(emailInfo,
                     outputTemplate: "{Timestamp:HH:mm:ss}\t{Level:u3}\t{SourceContext}\t{Message}{NewLine}{Exception}")
                .CreateLogger()
              )
        {
            logger.Error("Error occured (test)...");
            //CreateWebHostBuilder(args).Build().Run(); or here...
        }

        CreateWebHostBuilder(args).Build().Run();
    }

The email with test is sent but not when error of application occurs

I use Logger of microsoft extension in my ErrorController

public ErrorController(ILogger<ErrorController> logger)
    {
        this.logger = logger;
    }

then in a method of errorcontroller i call logger.LogError(exception);

       var feature = HttpContext.Features.Get<IExceptionHandlerFeature>();
        logger.LogError(feature.Error);

Solution

  • You're not telling the application to use SeriLog. Try following code.

    using (var logger = new LoggerConfiguration()
             .MinimumLevel.Error()
             .WriteTo.Email(emailInfo,
                 outputTemplate: "{Timestamp:HH:mm:ss}\t{Level:u3}\t{SourceContext}\t{Message}{NewLine}{Exception}")
            .CreateLogger())
    {
        logger.Error("Error occured (test)...");
        CreateWebHostBuilder(args)
             .UseSerilog(logger)
             .Build().Run();
    }
    

    Personally, I'm creating my logger instance in the Startup.Configure method, using the static Log.Logger property. But the above should work as well.

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            Log.Logger = new LoggerConfiguration()
                .ReadFrom.Configuration(this.Configuration)
                .CreateLogger();
            ...
        }
    

    I'm not very sure how well the default implementation works with SeriLog. You may need to remove all the logging settings from your appsettings.json file.