简体   繁体   English

从 .NET Core Program.cs 访问配置

[英]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").我正在尝试从配置服务部分的 Program.cs 访问配置部分 (appsettings.json) 以设置日志记录,当我使用 hostContext.Configuration.GetSection("AppSettings") 时,我得到 null。 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 ASP.NET Core 中 Program.Main 中的访问环境名称

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 ASP.NET 核心程序.cs配置 - ASP.NET Core program.cs configuration 如何从 ASP.NET Core 中的 Program.cs 访问 IWebHostEnvironment - How to access IWebHostEnvironment from Program.cs in ASP.NET Core .NET Core program.cs 和 Startup.cs 未命中 - .NET Core program.cs and Startup.cs not hit .NET核心从Program.cs传递命令行Args到Startup.cs - .NET core Pass Commandline Args to Startup.cs from Program.cs 在 program.cs dotNet Core 6 中添加配置服务 - add configuration services in program.cs dotNet Core 6 如何仅在 .NET 6 Program.cs 中添加配置? - How to add configuration in .NET 6 Program.cs only? 如何在不使用启动 class 的情况下将其迁移到我的 .NET 6 Program.cs 文件中? 代码来自 .NET Core 2.1,也在 Program.cs - How do I migrate this into my .NET 6 Program.cs file without using the startup class? The code is from .NET Core 2.1, also in Program.cs 将 .NET 核心从 2 升级到 3 后 Program.cs 中的 DI 停止工作 - DI in Program.cs stopped working after upgrade .NET Core from 2 to 3 将 IConfiguration 注入 .NET Core 3.0 中的 Program.cs(控制台应用程序) - Inject IConfiguration into Program.cs (Console App) in .NET Core 3.0 避免在ASP.NET Core Program.cs中使用静态值 - Avoid static value in ASP.NET Core Program.cs
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM