I am trying to access the Configuration sections (appsettings.json) from the Program.cs in Configure Services section to set up logging and I get null when I use hostContext.Configuration.GetSection("AppSettings"). Searched online for different answers but no luck whatsoever. What am I missing?
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();
}
});
}