1

I am using the recommended approach to configure Serilog with ASP.NET Core.

How to get ConnectionString from configuration in method Main to configure SQL Server sink?

public class Program {
  public static Int32 Main(String[] args) {

    Log.Logger = new LoggerConfiguration()
      .MinimumLevel.Debug()
      .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
      .Enrich.FromLogContext()
      .WriteTo.Console()
      .CreateLogger();

    try {
      CreateHostBuilder(args).Build().Run();
      return 0;
    } catch (Exception exception) {
      return 1;
    } finally {
      Log.CloseAndFlush();
    }

  }

  public static IHostBuilder CreateHostBuilder(String[] args) {

    IHostBuilder builder = Host.CreateDefaultBuilder(args);

    builder
      .UseSerilog()
      .ConfigureWebHostDefaults(builder => {

      builder
        .ConfigureAppConfiguration((context, configuration) => {

          IWebHostEnvironment environment = context.HostingEnvironment;

          configuration
            .AddJsonFile("settings.json", false, true)
            .AddJsonFile($"settings.{environment.EnvironmentName}.json", false, true)
            .AddEnvironmentVariables();

        }) 
        .UseStartup<Startup>();

    });

    return builder;      
  } 
} 

I am using: - Serilog: 2.9.0 - Serilog.Sinks.MSSqlServer: 5.3.0

In: .NET Core 3.1

1

1 Answer 1

1

You can get the environment:

var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");

Then use it to manually configure a builder just like you're doing below:

var configuration = new ConfigurationBuilder()
    .AddJsonFile("settings.json", false, true)
    .AddJsonFile($"settings.{environment}.json", false, true)
    .AddEnvironmentVariables()
    .Build();

Then get the connection string like normal:

var connectionString = configuration.GetConnectionString("...")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.