我正在使用推荐的方法用ASP.NET Core配置Serilog。
如何从Main方法中的配置中获取ConnectionString来配置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;
}
}
我使用的是:- Serilog: 2.9.0- Serilog.Sinks.MSSqlServer: 5.3.0
在:.NET Core 3.1
你可以得到环境。
var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
然后用它来手动配置一个构建器,就像你下面做的那样。
var configuration = new ConfigurationBuilder()
.AddJsonFile("settings.json", false, true)
.AddJsonFile($"settings.{environment}.json", false, true)
.AddEnvironmentVariables()
.Build();
然后像平常一样获取连接字符串
var connectionString = configuration.GetConnectionString("...")