簡體   English   中英

如何在服務啟動時讀取應用洞察密鑰

[英]How to read application insights key during service startup

例如,配置 ApplicationInsights 檢測密鑰的正確方法是什么,以便它可以在服務啟動期間(在IConfiguration可用之前)使用

public class Program
    {
        public static void Main(string[] args)
        {
            var appInsightsTelemetryConfiguration = TelemetryConfiguration.CreateDefault();

            //TODO: how to extract this key from config??
            appInsightsTelemetryConfiguration.InstrumentationKey = "I want to pull this key from config";

            Log.Logger = new LoggerConfiguration()
                    .Enrich.FromLogContext()
                    .WriteTo.Console()
                    .WriteTo.ApplicationInsights(appInsightsTelemetryConfiguration, TelemetryConverter.Traces)
                    .CreateLogger();

            try
            {
                Log.Information(Constants.Logging.Messages.SERVICE_STARTED, assembly.Name);
                CreateHostBuilder(args).Build().Run();
                return;
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, Constants.Logging.Messages.SERVICE_STARTED, assembly.Name);
                return;
            }
            finally
            {
                // make sure all batched messages are written.
                Log.CloseAndFlush();
            }
        }

您可以使用以下代碼:

    public static void Main(string[] args)
    {
        var appInsightsTelemetryConfiguration = TelemetryConfiguration.CreateDefault();

        //TODO: how to extract this key from config??
        //appInsightsTelemetryConfiguration.InstrumentationKey = "I want to pull this key from config";

        //use this code:
        var builder = new ConfigurationBuilder()
            .AddJsonFile($"appsettings.json", true, true)
            .AddEnvironmentVariables();

        var configuration = builder.Build();

        string myikey = configuration.GetSection("ApplicationInsights:InstrumentationKey").Value;
        appInsightsTelemetryConfiguration.InstrumentationKey = myikey;

        Log.Logger = new LoggerConfiguration()
                .Enrich.FromLogContext()
                .WriteTo.Console()
                .WriteTo.ApplicationInsights(appInsightsTelemetryConfiguration, TelemetryConverter.Traces)
                .CreateLogger();


       //other code

    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM