简体   繁体   中英

How to read application insights key during service startup

What is the correct way to configure ApplicationInsights instrumentation key so it can be used during service startup (before IConfiguration is available), for example

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();
            }
        }

You can use the code below:

    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

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM