Apa cara yang benar untuk mengonfigurasi kunci instrumentasi ApplicationInsights sehingga dapat digunakan selama startup layanan (sebelum IConfiguration tersedia), misalnya

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();
            }
        }
-1
Mark Cooper 11 November 2020, 23:35

1 menjawab

Jawaban Terbaik

Anda dapat menggunakan kode di bawah ini:

    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

    }
1
Ivan Yang 12 November 2020, 01:32