public static void Main(string[] args)
        {
            using (var channel = new InMemoryChannel())
            {
                var configuration = new ConfigurationBuilder()
                                    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: false)
                                    .Build();

                using (var serviceProvider = ConfigureService(configuration, channel))
                {
                    string exceptionMessage = null;

                    Console.WriteLine("Do you want this to break? Y/N");
                    var foo = Console.ReadLine();

                    var useRandomError = false;
                    int errorCount     = 0;

                    var shouldBreak = foo == "Y";
                    if (shouldBreak)
                    {
                        Console.WriteLine("Fair enough, we'll break in a bit");

                        Console.WriteLine("Should we use random errors?");
                        var shouldWe = Console.ReadLine();

                        useRandomError = string.Equals(shouldWe, "Y", StringComparison.OrdinalIgnoreCase);
                        if (useRandomError)
                        {
                            Console.WriteLine("Hooray! Random errors!");
                        }
                        else
                        {
                            Console.WriteLine("Boring...");
                            Console.WriteLine("Ok, so what would you like the exception message to be?");
                            exceptionMessage = Console.ReadLine();
                        }

                        Console.WriteLine("How many errors should we generate?");

                        var howManyErrorsString = Console.ReadLine();

                        errorCount = int.Parse(howManyErrorsString);
                    }
                    else
                    {
                        Console.WriteLine("Suit yourself, we won't break this time");
                    }

                    serviceProvider.GetService <TestService>().Run(shouldBreak, useRandomError, errorCount, exceptionMessage);
                }

                Console.WriteLine("Hello World!");

                channel.Flush();
                Thread.Sleep(1000);
            }
        }
Exemple #2
0
        public static void Initialize(ILogger customLogger)
        {
            IServiceCollection services = new ServiceCollection();

            IConfiguration config = GetConfiguration();

            services.AddSingleton(typeof(IConfiguration), config);

            ITelemetryChannel channel = new InMemoryChannel();

            services.AddSingleton(typeof(ITelemetryChannel), channel);

            if (customLogger == null)
            {
                services.AddLogging(builder =>
                {
                    if (config.GetSection(LoggingConsoleSection).Exists())
                    {
                        builder.AddConsole();
                    }

                    if (config.GetSection(LoggingApplicationInsightsSection).Exists())
                    {
                        if (!string.IsNullOrEmpty(config[LoggingApplicationInsightsInstrumentationKey]))
                        {
                            builder.AddApplicationInsights(config[LoggingApplicationInsightsInstrumentationKey], options => options.FlushOnDispose = true);
                        }
                    }

                    builder.AddConfiguration(config.GetSection(LoggingSection));
                });
            }
            else
            {
                services.AddSingleton(typeof(ILogger), customLogger);
            }

            services.Configure <TelemetryConfiguration>((o) =>
            {
                o.TelemetryChannel = channel;
                o.TelemetryInitializers.Add(new ApplicationInsightsTelemetryInitializer());
                o.TelemetryInitializers.Add(new OperationCorrelationTelemetryInitializer());
            });

            ServiceProvider = services.BuildServiceProvider();

            // The logging in the application uses an ILogger, not a ILogger<T>. So if the ILogger is not
            // present, re-register the service.
            ILogger baseLogger = ServiceProviderFactory.ServiceProvider.GetService <ILogger>();

            if (baseLogger == null)
            {
                ILogger categoryLogger = ServiceProviderFactory.ServiceProvider.GetService <ILogger <ILogger> >();
                services.AddSingleton(typeof(ILogger), categoryLogger);
                ServiceProvider = services.BuildServiceProvider();
            }
        }
        static void Main(string[] args)
        {
            // Create the DI container.
            IServiceCollection services = new ServiceCollection();

            // Uncomment the following lines for debugging AI.K8s.
            // Refer to https://github.com/microsoft/ApplicationInsights-Kubernetes/blob/develop/docs/SelfDiagnostics.MD for details.
            // var observer = new ApplicationInsightsKubernetesDiagnosticObserver(DiagnosticLogLevel.Trace);
            // ApplicationInsightsKubernetesDiagnosticSource.Instance.Observable.SubscribeWithAdapter(observer);

            // Add application insights for Kubernetes. Making sure this is called before services.Configure<TelemetryConfiguration>().
            services.AddApplicationInsightsKubernetesEnricher();

            // Channel is explicitly configured to do flush on it later.
            var channel = new InMemoryChannel();

            services.Configure <TelemetryConfiguration>(
                (config) =>
            {
                config.TelemetryChannel = channel;
            }
                );

            // Add the logging pipelines to use. We are using Application Insights only here.
            services.AddLogging(builder =>
            {
                // Optional: Apply filters to configure LogLevel Trace or above is sent to
                // Application Insights for all categories.
                builder.AddFilter <Microsoft.Extensions.Logging.ApplicationInsights.ApplicationInsightsLoggerProvider>("", LogLevel.Trace);
                builder.AddApplicationInsights("---Your AI instrumentation key---");

                // Optional: Show the logs in console at the same time
                builder.AddConsole();
            });

            // Build ServiceProvider.
            IServiceProvider  serviceProvider = services.BuildServiceProvider();
            ILogger <Program> logger          = serviceProvider.GetRequiredService <ILogger <Program> >();

            while (true)
            {
                // Begin a new scope. This is optional.
                using (logger.BeginScope(new Dictionary <string, object> {
                    { "Method", nameof(Main) }
                }))
                {
                    logger.LogInformation("Logger is working"); // this will be captured by Application Insights.
                }

                // Explicitly call Flush() followed by sleep is required in Console Apps.
                // This is to ensure that even if application terminates, telemetry is sent to the back-end.
                channel.Flush();
                Thread.Sleep(10000);
            }
        }
        public static async Task Main(string[] args)
        {
            // Channel is explicitly configured to do flush on it later.
            var channel = new InMemoryChannel();

            var host = new HostBuilder()
                       .ConfigureServices((context, services) =>
            {
                // Uncomment the following lines for debugging AI.K8s.
                // Refer to https://github.com/microsoft/ApplicationInsights-Kubernetes/blob/develop/docs/SelfDiagnostics.MD for details.
                // var observer = new ApplicationInsightsKubernetesDiagnosticObserver(DiagnosticLogLevel.Trace);
                // ApplicationInsightsKubernetesDiagnosticSource.Instance.Observable.SubscribeWithAdapter(observer);

                // Add application insights for Kubernetes. Making sure this is called before services.Configure<TelemetryConfiguration>().
                services.AddApplicationInsightsKubernetesEnricher();

                services.Configure <TelemetryConfiguration>(
                    (config) =>
                {
                    config.TelemetryChannel = channel;
                }
                    );

                // Add the logging pipelines to use. We are using Application Insights only here.
                services.AddLogging(builder =>
                {
                    // Optional: Apply filters to configure LogLevel Trace or above is sent to
                    // Application Insights for all categories.
                    builder.AddFilter <Microsoft.Extensions.Logging.ApplicationInsights.ApplicationInsightsLoggerProvider>
                        ("", LogLevel.Trace);
                    builder.AddApplicationInsights("----Your instrumentation key----");
                    builder.AddConsole();
                });

                // Register your services that implemented IHostedService interface. For example, SendAIEventService
                services.AddHostedService <SendAIEventService>();
            }).Build();

            IApplicationLifetime lifetime = host.Services.GetRequiredService <IApplicationLifetime>();

            lifetime.ApplicationStopping.Register(() =>
            {
                channel.Flush();
                // Work around Application Insights issue:
                // https://github.com/Microsoft/ApplicationInsights-dotnet/issues/407
                System.Threading.Thread.Sleep(TimeSpan.FromSeconds(2));
            });
            await host.RunAsync();
        }
        public void VerifySetConnectionString_SetsChannelDefaultEndpoint()
        {
            var connectionString = $"InstrumentationKey=00000000-0000-0000-0000-000000000000";

            var channel = new InMemoryChannel();

            var configuration = new TelemetryConfiguration
            {
                TelemetryChannel = channel,
                ConnectionString = connectionString,
            };

            Assert.AreEqual("00000000-0000-0000-0000-000000000000", configuration.InstrumentationKey);
            Assert.AreEqual("https://dc.services.visualstudio.com/", configuration.EndpointContainer.Ingestion.AbsoluteUri);
            Assert.AreEqual("https://dc.services.visualstudio.com/v2/track", channel.EndpointAddress);
        }
        public void VerifySetConnectionString_SetsChannelExpliticEndpoint()
        {
            var explicitEndpoint = "https://127.0.0.1/";
            var connectionString = $"InstrumentationKey=00000000-0000-0000-0000-000000000000;IngestionEndpoint={explicitEndpoint}";

            var channel = new InMemoryChannel();

            var configuration = new TelemetryConfiguration
            {
                TelemetryChannel = channel,
                ConnectionString = connectionString,
            };

            Assert.AreEqual("00000000-0000-0000-0000-000000000000", configuration.InstrumentationKey);
            Assert.AreEqual(explicitEndpoint, configuration.EndpointContainer.Ingestion.AbsoluteUri);
            Assert.AreEqual(explicitEndpoint + "v2/track", channel.EndpointAddress);
        }
Exemple #7
0
 void ObservePreferenceChange(PreferenceChange change)
 {
     if (change.Key == Prefs.Telemetry.Enabled.Key)
     {
         enabled = Prefs.Telemetry.Enabled.GetValue();
         if (!enabled)
         {
             Log.Info(TAG, "Telemetry disabled.");
             appInsightsClient = null;
             // Not bothering to Dispose channel, because that will trigger a synchronous Flush
             channel = null;
         }
         else if (appInsightsClient == null)
         {
             Log.Info(TAG, "Telemetry will be enabled after restart.");
         }
     }
 }
        static void Main(string[] args)
        {
            // Create the DI container.
            IServiceCollection services = new ServiceCollection();

            // Channel is explicitly configured to do flush on it later.
            var channel = new InMemoryChannel();

            services.Configure <TelemetryConfiguration>(
                (config) =>
            {
                config.TelemetryChannel = channel;
            }
                );

            // Add the logging pipelines to use. We are using Application Insights only here.
            services.AddLogging(builder =>
            {
                // Optional: Apply filters to configure LogLevel Trace or above is sent to
                // Application Insights for all categories.
                builder.AddFilter <Microsoft.Extensions.Logging.ApplicationInsights.ApplicationInsightsLoggerProvider>("", LogLevel.Trace);
                builder.AddApplicationInsights("---Your AI instrumentation key---");
            });

            // Add application insights for Kubernetes.
            services.AddApplicationInsightsKubernetesEnricher();

            // Build ServiceProvider.
            IServiceProvider  serviceProvider = services.BuildServiceProvider();
            ILogger <Program> logger          = serviceProvider.GetRequiredService <ILogger <Program> >();

            // Begin a new scope. This is optional.
            using (logger.BeginScope(new Dictionary <string, object> {
                { "Method", nameof(Main) }
            }))
            {
                logger.LogInformation("Logger is working"); // this will be captured by Application Insights.
            }

            // Explicitly call Flush() followed by sleep is required in Console Apps.
            // This is to ensure that even if application terminates, telemetry is sent to the back-end.
            channel.Flush();
            Thread.Sleep(1000);
        }
    static void Main(string[] args)
    {
        // Create DI container.
        IServiceCollection services = new ServiceCollection();

        var channel = new InMemoryChannel();

        services.Configure <TelemetryConfiguration>(
            (config) =>
        {
            config.TelemetryChannel = channel;
        }
            );

        // Add the logging pipelines to use. We are using Application Insights only here.
        services.AddLogging(loggingBuilder =>
        {
            // Optional: Apply filters to configure LogLevel Trace or above is sent to ApplicationInsights for all
            // categories.
            loggingBuilder.AddFilter <ApplicationInsightsLoggerProvider>("", LogLevel.Trace);
            loggingBuilder.AddApplicationInsights("***");
        });

        // Build ServiceProvider.
        IServiceProvider serviceProvider = services.BuildServiceProvider();

        ILogger <Program> logger = serviceProvider.GetRequiredService <ILogger <Program> >();


        logger.LogCritical("critical message working");
        // Begin a new scope. This is optional. Epecially in case of AspNetCore request info is already
        // present in scope.
        using (logger.BeginScope(new Dictionary <string, object> {
            { "Method", nameof(Main) }
        }))
        {
            logger.LogWarning("Logger is working - warning");         // this will be captured by Application Insights.
        }

        channel.Flush();
        Thread.Sleep(1000);
    }
Exemple #10
0
        static ServiceProviderFactory()
        {
            IServiceCollection services = new ServiceCollection();

            IConfiguration config = GetConfiguration();

            services.AddSingleton(typeof(IConfiguration), config);

            ITelemetryChannel channel = new InMemoryChannel();

            services.AddSingleton(typeof(ITelemetryChannel), channel);

            services.AddLogging(builder =>
            {
                if (config.GetSection(LoggingConsoleSection).Exists())
                {
                    builder.AddConsole();
                }

                if (config.GetSection(LoggingApplicationInsightsSection).Exists())
                {
                    if (!string.IsNullOrEmpty(config[LoggingApplicationInsightsInstrumentationKey]))
                    {
                        builder.AddApplicationInsights(config[LoggingApplicationInsightsInstrumentationKey], options => options.FlushOnDispose = true);
                    }
                }

                builder.AddConfiguration(config.GetSection(LoggingSection));
            });

            services.Configure <TelemetryConfiguration>((o) =>
            {
                o.TelemetryChannel = channel;
                o.TelemetryInitializers.Add(new ApplicationInsightsTelemetryInitializer());
                o.TelemetryInitializers.Add(new OperationCorrelationTelemetryInitializer());
            });

            ServiceProvider = services.BuildServiceProvider();
        }
Exemple #11
0
        private static void InitializeTelemetry()
        {
            var isDebugging = Debugger.IsAttached;
            var config      = TelemetryConfiguration.CreateDefault();

            if (!isDebugging)
            {
                config.InstrumentationKey = "9fcef3c7-f401-41c7-9e91-1f6029c8dcc3";
            }

            var dependencyTracking = new DependencyTrackingTelemetryModule();

            dependencyTracking.ExcludeComponentCorrelationHttpHeadersOnDomains.Add("core.windows.net");
            dependencyTracking.Initialize(config);

            config.TelemetryInitializers.Add(new HttpDependenciesParsingTelemetryInitializer());
            var channel = new InMemoryChannel {
                DeveloperMode = isDebugging
            };

            config.TelemetryChannel = channel;

            s_telemetryClient = new TelemetryClient(config);
        }
        private static ServiceProvider ConfigureService(IConfigurationRoot configuration, InMemoryChannel channel)
        {
            var services = new ServiceCollection()
                           .Configure <TelemetryConfiguration>((config) =>
            {
                config.TelemetryChannel = channel;
            })
                           .AddLogging(builder =>
            {
                var consoleEnabled = configuration.GetValue <bool>("Console:Enabled");

                if (consoleEnabled)
                {
                    builder.AddConsole();
                }

                var applicationInsightsInstrumentationKey = configuration.GetValue <string>("ApplicationInsights:InstrumentationKey");

                if (!string.IsNullOrWhiteSpace(applicationInsightsInstrumentationKey))
                {
                    builder.AddApplicationInsights(applicationInsightsInstrumentationKey);
                }
            })
                           .AddScoped <TestService>();

            services.AddApplicationInsightsTelemetryWorkerService();

            return(services.BuildServiceProvider());
        }
Exemple #13
0
        private static async Task Main(string[] args)
        {
            // Channel is explicitly configured to do flush on it later.
            var channel = new InMemoryChannel {
                SendingInterval = TimeSpan.FromSeconds(10)
            };

            try
            {
                await new HostBuilder()
                .ConfigureHostConfiguration(configuration =>
                {
                    configuration
                    .AddEnvironmentVariables("NETCORE_")
                    .AddCommandLine(args);
                })
                .ConfigureAppConfiguration((hostContext, configuration) =>
                {
                    configuration
                    .AddJsonFile("appsettings.json", false, true)
                    .AddJsonFile($"appsettings.{hostContext.HostingEnvironment.EnvironmentName}.json",
                                 false, true);

                    //optionally add in azure app config by setting a conneciton string AppConfig
                    var appConfig = configuration.Build().GetConnectionString("AppConfig");
                    if (!string.IsNullOrWhiteSpace(appConfig))
                    {
                        configuration.AddAzureAppConfiguration(appConfig);
                    }
                })
                .ConfigureLogging((hostContext, logging) =>
                {
                    var logConfig = hostContext.Configuration.GetSection("Logging");

                    logging
                    .AddConfiguration(logConfig)
                    .AddDebug()
                    .AddConsole()
                    .AddEventSourceLogger()
                    .AddApplicationInsights();
                })
                .ConfigureServices((hostContext, services) =>
                {
                    services
                    .AddApplicationInsightsTelemetryWorkerService()
                    .Configure <TelemetryConfiguration>(telemetry =>
                    {
                        telemetry.TelemetryChannel = channel;
                        if (string.IsNullOrEmpty(telemetry.InstrumentationKey))
                        {
                            throw new ArgumentNullException(nameof(telemetry.InstrumentationKey));
                        }
                    })
                    .AddSingleton <IPickANumber, PickANumber>()
                    .AddTransient <ILooper, Looper>()
                    .AddTransient <IMyTelemetry, MyTelemetry>()
                    .AddHostedService <Worker>();
                })
                .RunConsoleAsync();
            }
            finally
            {
                // Explicitly call Flush() followed by sleep is required in ConsoleApp Apps.
                // This is to ensure that even if application terminates, telemetry is sent to the back-end.
                channel.Flush();
                Thread.Sleep(5000);
            }
        }
Exemple #14
0
        public Client(Guid sessionid, ClientAppHostEnvironment host, UpdaterService updater)
        {
            if (Interactive.Client.CommandLineTool.TestDriver.ShouldRun)
            {
                return;
            }

            PreferenceStore.Default.Subscribe(ObservePreferenceChange);

            try {
                if (!Prefs.Telemetry.Enabled.GetValue())
                {
                    Log.Info(TAG, "Telemetry is disabled");
                    return;
                }

                // InMemoryChannel is the default channel, but we set it up manually here so we can tweak several
                // default settings that are undesirable for desktop apps.
                channel = new InMemoryChannel {
                    // Defaults to 30s, but since we are changing buffer.Capacity to 1, we can make this infinite and
                    // avoid pointlessly waking up InMemoryTransmitter's Runner.
                    SendingInterval = Timeout.InfiniteTimeSpan,
                };

                // There is no reasonable public API for changing the buffer capacity at this time.
                // You can achieve it by turning on DeveloperMode, but that has other consequences.
                // So we reflect.
                //
                // The default Capacity is 500, which is far too large for us (and perhaps most non-server apps).
                // We want to avoid having to perform a blocking Flush call on the UI thread, and since our events
                // are currently few and far between, we set Capacity to 1 to essentially get auto-flush.
                var channelBuffer = typeof(InMemoryChannel)
                                    .GetField("buffer", BindingFlags.NonPublic | BindingFlags.Instance)
                                    .GetValue(channel);
                channelBuffer
                .GetType()
                .GetProperty("Capacity", BindingFlags.Public | BindingFlags.Instance)
                .SetValue(channelBuffer, 1);

                var config = new TelemetryConfiguration("@TELEMETRY_INSTRUMENTATION_KEY@", channel);

                appInsightsClient = new TelemetryClient(config);

                appInsightsClient.Context.Session.Id             = sessionid.ToString();
                appInsightsClient.Context.Device.OperatingSystem = host.OSName.ToString();

                // TODO: Make these GlobalProperties when we bump to 2.7.0-beta3 or later
                var globalProperties = appInsightsClient.Context.Properties;
                globalProperties.Add(
                    "Product Version",
                    BuildInfo.VersionString);
                globalProperties.Add(
                    "Build Hash",
                    BuildInfo.Hash);
                globalProperties.Add(
                    "OS Platform",
                    Runtime.CurrentProcessRuntime.OSPlatform.ToString());
                globalProperties.Add(
                    "OS Architecture",
                    RuntimeInformation.OSArchitecture.ToString());
                globalProperties.Add(
                    "Process Architecture",
                    Runtime.CurrentProcessRuntime.Architecture.ToString());
                globalProperties.Add(
                    "Runtime Identifier",
                    Runtime.CurrentProcessRuntime.RuntimeIdentifier);
                globalProperties.Add(
                    "OS Version",
                    host.OSVersion.ToString());
                globalProperties.Add(
                    "Release Candidate Level",
                    ((byte)BuildInfo.Version.CandidateLevel).ToString());
                globalProperties.Add(
                    "Release Candidate Level Name",
                    BuildInfo.Version.CandidateLevel.ToString().ToLowerInvariant());
                globalProperties.Add(
                    "Machine ID",
                    Sha256Hasher.Hash(MacAddressGetter.GetMacAddress()));
                globalProperties.Add(
                    "Update Channel", updater.UpdateChannel);

                enabled = true;
            } catch (Exception e) {
                LogErrorWithoutTelemetry(e, "Unable to create AppInsights client for telemetry");
            }
        }