c# - 从 .NET Core Program.cs 访问配置
问题描述
我正在尝试从配置服务部分中的 Program.cs 访问配置部分 (appsettings.json) 以设置日志记录,当我使用 hostContext.Configuration.GetSection("AppSettings") 时我得到空值。在网上搜索了不同的答案,但没有任何运气。我错过了什么?
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseEnvironment(Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT"))
.UseWindowsService()
.ConfigureLogging(loggerFactory =>
{
loggerFactory.AddEventLog();
loggerFactory.AddEventSourceLogger();
})
.ConfigureAppConfiguration((hostingContext, config) =>
{
var env = Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT");
hostingContext.HostingEnvironment.EnvironmentName = env;
config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env}.json", optional: true, reloadOnChange: true)
.Build();
if (env.Contains("Development"))
{
var appAssembly = Assembly.Load(new AssemblyName(hostingContext.HostingEnvironment.ApplicationName));
if (appAssembly != null)
{
config.AddUserSecrets(appAssembly, optional: true);
}
}
config.AddEnvironmentVariables();
if (args != null)
{
config.AddCommandLine(args);
}
})
.UseSerilog()
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<Worker>();
services.Configure<AppSettings>(hostContext.Configuration.GetSection("AppSettings"));
services.AddScoped<IMarketplaceOrderProcessor, MarketplaceOrderProcessor>();
IConfiguration configuration = hostContext.Configuration;
var env = hostContext.HostingEnvironment;
var logLevel = (LogEventLevel)Enum.Parse(typeof(LogEventLevel), configuration.GetSection("Serilog").GetSection("LogLevel").Value);
var retentionPolicy = (LogGroupRetentionPolicy)Enum.Parse(typeof(LogGroupRetentionPolicy), configuration.GetSection("Serilog").GetSection("RententionPolicy").Value);
var levelSwitch = new LoggingLevelSwitch();
levelSwitch.MinimumLevel = logLevel;
// customer formatter
var formatter = new CustomLogFormatter();
var options = new CloudWatchSinkOptions
{
LogGroupName = configuration.GetSection("Serilog").GetSection("LogGroup").Value,
TextFormatter = formatter,
MinimumLogEventLevel = logLevel,
BatchSizeLimit = 100,
QueueSizeLimit = 10000,
Period = TimeSpan.FromSeconds(10),
CreateLogGroup = true,
LogStreamNameProvider = new DefaultLogStreamProvider(),
RetryAttempts = 5,
LogGroupRetentionPolicy = retentionPolicy
};
var providerAwsId = configuration.GetSection("AppSettings").GetSection("s3AwsSecretAccessKeyId").Value;
var providerAwsKey = configuration.GetSection("AppSettings").GetSection("s3AwsSecretAccessKey").Value;
var awsCredentials = new BasicAWSCredentials(providerAwsId, providerAwsKey);
var region = RegionEndpoint.GetBySystemName(configuration.GetSection("Serilog").GetSection("Region").Value);
var client = new AmazonCloudWatchLogsClient(awsCredentials, region);
if (env.EnvironmentName.Contains("Development"))
{
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration, "Serilog")
.Enrich.FromLogContext()
.Enrich.WithThreadId()
.Enrich.WithThreadName()
.Enrich.WithNewRelicLogsInContext()
.WriteTo.Console()
.WriteTo.Async(a => a.File(formatter: new NewRelicFormatter(), path: Environment.GetEnvironmentVariable("SVC_NEWRELIC"), rollingInterval: RollingInterval.Day, rollOnFileSizeLimit: true, buffered: true))
.WriteTo.AmazonCloudWatch(options, client)
.CreateLogger();
}
else
{
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration, "Serilog")
.Enrich.FromLogContext()
.Enrich.WithThreadId()
.Enrich.WithThreadName()
.Enrich.WithNewRelicLogsInContext()
.WriteTo.Console()
.WriteTo.Async(a => a.File(formatter: new NewRelicFormatter(), path: Environment.GetEnvironmentVariable("SVC_NEWRELIC"), rollingInterval: RollingInterval.Day, rollOnFileSizeLimit: true, buffered: true))
.CreateLogger();
}
});
}
解决方案
var env = Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT");
hostingContext.HostingEnvironment.EnvironmentName = env;
var configuration = new ConfigurationBuilder()
.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath)
.AddJsonFile($"appsettings.{env}.json", optional: true, reloadOnChange: true)
.Build();
推荐阅读
- networking - 使用ansible根据网络显示特殊文件
- rest - 我应该在 REST 上使用 WebSockets 吗?
- c# - 为什么 MVC 绑定模型需要属性而不是字段
- javascript - 动态设置从 JavaScript 模块导出的变量
- python-3.x - python字节到字符串转换中的t,n是什么意思?
- r - 使用 R 包 DT 使用 autowidth 和 scrollX 渲染表格
- laravel - 将不同的数据库查询合并到一个查询中
- c# - 文件 packages.config.md5sum 的用途
- angular - 属性返回未定义
- html - width:100% 当你点击一个项目时