简体   繁体   中英

Access Configuration from .NET Core Program.cs

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();
            }                   
        });
}
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();

This one solved my problem.

var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
var isDevelopment = environment == EnvironmentName.Development;

Access environment name in Program.Main in ASP.NET Core

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM