我不想直接输入应用程序洞察力的键来注册日志

时间:2019-03-26 08:24:57

标签: c# logging asp.net-core azure-application-insights

我不想在Program.cs中键入应用程序洞察力的密钥,我可以在某些配置文件中还是在其他位置键入它?这是一个ASP .Net Core

我想在日志的应用程序见解中包含一个注册,但要进行修改。现在我有了一个寄存器,但是我在Program.cs中键入密钥,并且在更改环境时遇到“问题”。您是否知道在Program.cs上动态键入此密钥的任何方法,或者可以在程序的其他位置进行此声明。

这是Program.cs。它从Main开始,然后在BuildWebHost启动后,在其中加载应用程序见解的关键,这就是我要更改的地方:

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>()
        .ConfigureLogging(logging =>
        {
                logging.AddApplicationInsights("db0fe38d-c208-8ed7-23e4ef4479bb");

                // Optional: Apply filters to configure LogLevel Trace or above is sent to
                // ApplicationInsights for all categories.
                logging.AddFilter<ApplicationInsightsLoggerProvider>("", LogLevel.Trace);

                // Additional filtering For category starting in "Microsoft",
                // only Warning or above will be sent to Application Insights.
                logging.AddFilter<ApplicationInsightsLoggerProvider>("Microsoft", LogLevel.Warning);
        }).Build();

我怎么说,我会避免在程序上键入key,我想从配置文件中获取此参数或在另一个位置输入此声明

2 个答案:

答案 0 :(得分:1)

由于它是ASP.NET Core应用程序,因此可以使用注入{strong> WebHostBuilderContext 的ConfigureLogging扩展方法来检索配置:

 public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>()
        .ConfigureLogging((hostingContext, logging) =>
        {
                var appInsightKey =  hostingContext.Configuration["MyAppInsight"];
                logging.AddApplicationInsights(appInsightKey);

                // Optional: Apply filters to configure LogLevel Trace or above is sent to
                // ApplicationInsights for all categories.
                logging.AddFilter<ApplicationInsightsLoggerProvider>("", LogLevel.Trace);

                // Additional filtering For category starting in "Microsoft",
                // only Warning or above will be sent to Application Insights.
                logging.AddFilter<ApplicationInsightsLoggerProvider>("Microsoft", LogLevel.Warning);
        }).Build();

答案 1 :(得分:1)

只需添加UseApplicationInsights(),然后删除检测键(假定​​在appsettings.json中设置的检测键)即可。

如下所示的示例代码,在我这一边效果很好:

        public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
        .UseApplicationInsights()  // add this line of code, and it will auto-read ikey from appsettings.json.
        .UseStartup<Startup>()
        .ConfigureLogging(logging =>
        {
            //then you can remove instrumentation key from here.
            logging.AddApplicationInsights();
            logging.AddFilter<ApplicationInsightsLoggerProvider>("", LogLevel.Trace);


            logging.AddFilter<ApplicationInsightsLoggerProvider>("Microsoft", LogLevel.Warning);
        }).Build();
相关问题