.net core 3.1 console app serilog sinks email configuration

Cenk 1 Reputation point
2021-08-11T06:06:19.217+00:00

Hello guys,

I would like to read the email configuration from serilog.json but couldn't figure it out.

Here is my main:

class Program
    {
        static async Task Main(string[] args)
        {


            Log.Logger = new LoggerConfiguration()
                .MinimumLevel.Information()
                .Enrich.FromLogContext()
                .WriteTo.Console()
                .WriteTo.File("log-.txt", rollingInterval: RollingInterval.Day)
                .WriteTo.Email(new EmailConnectionInfo
                {
                    FromEmail = "test@test.com",
                    ToEmail = "anon@user ",
                    MailServer = "smtp.yandex.com.tr",
                    NetworkCredentials = new NetworkCredential
                    {
                        UserName = "abc",
                        Password = "123"
                    },
                    EnableSsl = false,
                    Port = 587,
                    EmailSubject = "Shipment Service Error"
                }, restrictedToMinimumLevel: LogEventLevel.Error, batchPostingLimit: 1)
                .CreateLogger();

            var builder = new HostBuilder()
                .ConfigureServices((hostContext, services) =>
                {
                    //Serilog
                    services.AddLogging(loggingBuilder =>
                        loggingBuilder.AddSerilog(dispose: true));

                    //Setting up API Client
                    services.AddHttpClient("ShipmentClient", client =>
                    {
                        client.BaseAddress =
                            new Uri("https://test.com/abc/");

                        client.DefaultRequestHeaders.Add("Accept", "application/json");
                    });

                    services.AddSingleton<IHostedService, BusinessService>();

                    //Setting up app settings configuration
                    var config = LoadConfiguration();
                    services.AddSingleton(config);


                });

            await builder.RunConsoleAsync();
        }

        public static IConfiguration LoadConfiguration()
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddJsonFile(path: "serilog.json", optional: false, reloadOnChange: true);

            return builder.Build();
        }
    }

Here is my serilog.json:

{
  "Serilog": {
    "LevelSwitches": {
      "$consoleSwitch": "Verbose",
      "$fileSwitch": "Verbose"
    },
    "Using": [
      "Serilog.Sinks.Console",
      "Serilog.Sinks.File"
    ],
    "MinimumLevel": "Verbose",
    "WriteTo": [
      {
        "Name": "Console",
        "Args": {
          "levelSwitch": "$consoleSwitch"
        }
      },
      {
        "Name": "File",
        "Args": {
          "path": "Logs/log.txt",
          "levelSwitch": "$fileSwitch"
        }
      }
    ]
  }
}
.NET CLI
.NET CLI
A cross-platform toolchain for developing, building, running, and publishing .NET applications.
326 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Daniel Zhang-MSFT 9,621 Reputation points
    2021-08-12T01:39:21.483+00:00

    Hi Cenk-6470,
    Based on your code, what specific problem did you encounter?
    And to use Serilog.Settings.Configuration, install the Nuget package, and configure you logger like :

    var config = new ConfigurationBuilder()  
        .AddJsonFile(fileName, optional: false)   
        .Build();  
      
    new LoggerConfiguration().ReadFrom.Configuration(config)  
        // snip ...  
        .CreateLogger();  
    

    More details please refer to the following links:
    Serilog Settings documentation
    Serilog.Settings.Configuration
    Best Regards,
    Daniel Zhang


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments