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

问题描述 投票:0回答:2

我不想在Program.cs中键入应用程序洞察的关键字,我可以在某个配置文件或其他地方输入它吗?这是一个ASP .Net核心

我想在我的日志的应用程序洞察中包含一个注册表,但需要修改。现在我有一个寄存器,但是我在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();

我怎么说,我会避免在程序上输入密钥,我想从配置文件中取出这个参数,或者在另一个地方输入这个声明

c# logging asp.net-core azure-application-insights
2个回答
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();

1
投票

由于它是ASP.NET Core应用程序,因此您可以使用注入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();
© www.soinside.com 2019 - 2024. All rights reserved.