/// <summary>
        /// Initialize method is called after all configuration properties have been loaded from the configuration.
        /// </summary>
        public void Initialize(TelemetryConfiguration configuration)
        {
            try
            {
                if (!this.IsInitialized)
                {
                    EventCounterCollectorEventSource.Log.ModuleIsBeingInitializedEvent(this.Counters?.Count ?? 0);

                    if (this.Counters.Count <= 0)
                    {
                        EventCounterCollectorEventSource.Log.EventCounterCollectorNoCounterConfigured();
                    }

                    this.client = new TelemetryClient(configuration);
                    this.client.Context.GetInternalContext().SdkVersion = SdkVersionUtils.GetSdkVersion("evtc:");
                    this.eventCounterListener = new EventCounterListener(this.client, this.Counters, this.refreshInternalInSecs, this.UseEventSourceNameAsMetricsNamespace);
                    this.IsInitialized        = true;
                    EventCounterCollectorEventSource.Log.ModuleInitializedSuccess();
                }
            }
            catch (Exception ex)
            {
                EventCounterCollectorEventSource.Log.EventCounterCollectorError("Initialization", ex.Message);
            }
        }
        /// <summary>
        /// Initializes the telemetry module and starts tracing EventSources specified via <see cref="Sources"/> property.
        /// </summary>
        /// <param name="configuration">Module configuration.</param>
        public void Initialize(TelemetryConfiguration configuration)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }

            this.client = new TelemetryClient(configuration);
            this.client.Context.GetInternalContext().SdkVersion = SdkVersionUtils.GetSdkVersion("evl:");

            if (this.Sources.Count == 0)
            {
                EventSourceListenerEventSource.Log.NoSourcesConfigured(nameof(EventSourceListener.EventSourceTelemetryModule));
                return;
            }

            try
            {
                if (this.initialized)
                {
                    // Source listening requests might have changed between initializations. Let's start from a clean slate
                    EventSource enabledEventSource = null;
                    while (this.enabledEventSources.TryDequeue(out enabledEventSource))
                    {
                        this.DisableEvents(enabledEventSource);
                    }
                }

                // Set the initialized flag now to ensure that we do not miss any sources that came online as we are executing the initialization
                // (OnEventSourceCreated() might have been called on a separate thread). Worst case we will attempt to enable the same source twice
                // (with same settings), but that is OK, as the semantics of EnableEvents() is really "update what is being tracked", so it is fine
                // to call it multiple times for the same source.
                this.initialized = true;

                if (this.appDomainEventSources != null)
                {
                    // Decide if there is disable event source listening requests
                    if (this.DisabledSources.Any())
                    {
                        this.enabledOrDisabledEventSourceTestResultCache = new ConcurrentDictionary <string, bool>();
                        this.eventWrittenHandlerPicker = this.OnEventWrittenIfSourceNotDisabled;
                    }
                    else
                    {
                        this.eventWrittenHandlerPicker = this.onEventWrittenHandler;
                    }

                    // Enumeration over concurrent queue is thread-safe.
                    foreach (EventSource eventSourceToEnable in this.appDomainEventSources)
                    {
                        this.EnableAsNecessary(eventSourceToEnable);
                    }
                }
            }
            finally
            {
                // No matter what problems we encounter with enabling EventSources, we should note that we have been initialized.
                this.initialized = true;
            }
        }
Exemplo n.º 3
0
        private void InitializeServiceClient(TelemetryConfiguration configuration)
        {
            if (this.serviceClient != null)
            {
                // service client has been passed through a constructor, we don't need to do anything
                return;
            }

            Uri serviceEndpointUri;

            if (string.IsNullOrWhiteSpace(this.QuickPulseServiceEndpoint))
            {
                // endpoint is not specified in configuration, use the default one
                serviceEndpointUri = QuickPulseDefaults.ServiceEndpoint;
            }
            else
            {
                // endpoint appears to have been specified in configuration, try using it
                try
                {
                    serviceEndpointUri = new Uri(this.QuickPulseServiceEndpoint);
                }
                catch (Exception e)
                {
                    throw new ArgumentException(
                              string.Format(
                                  CultureInfo.InvariantCulture,
                                  "Error initializing QuickPulse module. QPS endpoint is not a correct URI: '{0}'",
                                  this.QuickPulseServiceEndpoint),
                              e);
                }
            }

            // create the default production implementation of the service client with the best service endpoint we could get
            string instanceName    = GetInstanceName(configuration);
            string streamId        = GetStreamId();
            string machineName     = Environment.MachineName;
            var    assemblyVersion = SdkVersionUtils.GetSdkVersion(null);
            bool   isWebApp        = PerformanceCounterUtility.IsWebAppRunningInAzure();
            int?   processorCount  = PerformanceCounterUtility.GetProcessorCount(isWebApp);

            this.serviceClient = new QuickPulseServiceClient(
                serviceEndpointUri,
                instanceName,
                streamId,
                machineName,
                assemblyVersion,
                this.timeProvider,
                isWebApp,
                processorCount ?? 0);

            QuickPulseEventSource.Log.TroubleshootingMessageEvent(
                string.Format(
                    CultureInfo.InvariantCulture,
                    "Service client initialized. Endpoint: '{0}', instance name: '{1}', assembly version: '{2}'",
                    serviceEndpointUri,
                    instanceName,
                    assemblyVersion));
        }
        /// <summary>
        /// Initialize method is called after all configuration properties have been loaded from the configuration.
        /// </summary>
        public void Initialize(TelemetryConfiguration configuration)
        {
            if (!this.isInitialized)
            {
                lock (this.lockObject)
                {
                    if (!this.isInitialized)
                    {
                        PerformanceCollectorEventSource.Log.ModuleIsBeingInitializedEvent(
                            string.Format(
                                CultureInfo.InvariantCulture,
                                "Custom counters count: '{0}'",
                                Counters?.Count ?? 0));

                        if (configuration == null)
                        {
                            throw new ArgumentNullException(nameof(configuration));
                        }

                        if (!this.defaultCountersInitialized)
                        {
                            this.DefaultCounters.Add(new PerformanceCounterCollectionRequest(@"\Process(??APP_WIN32_PROC??)\% Processor Time", @"\Process(??APP_WIN32_PROC??)\% Processor Time"));
                            this.DefaultCounters.Add(new PerformanceCounterCollectionRequest(@"\Process(??APP_WIN32_PROC??)\% Processor Time Normalized", @"\Process(??APP_WIN32_PROC??)\% Processor Time Normalized"));
                            this.DefaultCounters.Add(new PerformanceCounterCollectionRequest(@"\Memory\Available Bytes", @"\Memory\Available Bytes"));
#if !NETSTANDARD2_0 // Exclude those counters which don't exist for .netcore
                            this.DefaultCounters.Add(new PerformanceCounterCollectionRequest(@"\ASP.NET Applications(??APP_W3SVC_PROC??)\Requests/Sec", @"\ASP.NET Applications(??APP_W3SVC_PROC??)\Requests/Sec"));
                            this.DefaultCounters.Add(new PerformanceCounterCollectionRequest(@"\.NET CLR Exceptions(??APP_CLR_PROC??)\# of Exceps Thrown / sec", @"\.NET CLR Exceptions(??APP_CLR_PROC??)\# of Exceps Thrown / sec"));
                            this.DefaultCounters.Add(new PerformanceCounterCollectionRequest(@"\ASP.NET Applications(??APP_W3SVC_PROC??)\Request Execution Time", @"\ASP.NET Applications(??APP_W3SVC_PROC??)\Request Execution Time"));
                            this.DefaultCounters.Add(new PerformanceCounterCollectionRequest(@"\ASP.NET Applications(??APP_W3SVC_PROC??)\Requests In Application Queue", @"\ASP.NET Applications(??APP_W3SVC_PROC??)\Requests In Application Queue"));
#endif
                            this.DefaultCounters.Add(new PerformanceCounterCollectionRequest(@"\Process(??APP_WIN32_PROC??)\Private Bytes", @"\Process(??APP_WIN32_PROC??)\Private Bytes"));
                            this.DefaultCounters.Add(new PerformanceCounterCollectionRequest(@"\Process(??APP_WIN32_PROC??)\IO Data Bytes/sec", @"\Process(??APP_WIN32_PROC??)\IO Data Bytes/sec"));
                            if (!PerformanceCounterUtility.IsWebAppRunningInAzure())
                            {
                                this.DefaultCounters.Add(new PerformanceCounterCollectionRequest(@"\Processor(_Total)\% Processor Time", @"\Processor(_Total)\% Processor Time"));
                            }
                        }

                        if (!this.EnableIISExpressPerformanceCounters && IsRunningUnderIisExpress())
                        {
                            PerformanceCollectorEventSource.Log.RunningUnderIisExpress();
                            return;
                        }

                        this.telemetryConfiguration = configuration;
                        this.client = new TelemetryClient(configuration);
                        this.client.Context.GetInternalContext().SdkVersion = SdkVersionUtils.GetSdkVersion(PerformanceCounterUtility.SDKVersionPrefix());

                        this.lastRefreshTimestamp = DateTime.MinValue;

                        this.timer = new Timer(this.TimerCallback);

                        // schedule the first tick
                        this.timer.ScheduleNextTick(this.collectionPeriod);
                        this.isInitialized = true;
                    }
                }
            }
        }
Exemplo n.º 5
0
        public SqlClientDiagnosticSourceListener(TelemetryConfiguration configuration)
        {
            this.client = new TelemetryClient(configuration);
            this.client.Context.GetInternalContext().SdkVersion =
                SdkVersionUtils.GetSdkVersion("rdd" + RddSource.DiagnosticSourceCore + ":");

            this.subscriber = new SqlClientDiagnosticSourceSubscriber(this);
        }
Exemplo n.º 6
0
        /// <summary>
        /// Initializes the telemetry module.
        /// </summary>
        /// <param name="configuration">Telemetry configuration to use for initialization.</param>
        public void Initialize(TelemetryConfiguration configuration)
        {
            this.telemetryClient = new TelemetryClient(configuration);
            this.telemetryClient.Context.GetInternalContext().SdkVersion = SdkVersionUtils.GetSdkVersion("web:");

            if (configuration != null && configuration.TelemetryChannel != null)
            {
                this.telemetryChannelEnpoint = configuration.TelemetryChannel.EndpointAddress;
            }
        }
Exemplo n.º 7
0
        /// <summary>
        /// Initializes a new instance of the ApplicationInsightsTraceListener class.
        /// If empty or null instrumentation key is passed, it will fall back to the one specified in ApplicationInsights.config file.
        /// </summary>
        /// <param name="instrumentationKey">Instrumentation Key of your application.</param>
        public ApplicationInsightsTraceListener(string instrumentationKey)
        {
            this.TelemetryClient = new TelemetryClient();
            if (!string.IsNullOrEmpty(instrumentationKey))
            {
                this.TelemetryClient.Context.InstrumentationKey = instrumentationKey;
            }

            this.TelemetryClient.Context.GetInternalContext().SdkVersion = SdkVersionUtils.GetSdkVersion("sd:");
        }
        /// <summary>
        /// Initializes the telemetry module and starts tracing DiagnosticSources specified via the <see cref="Sources"/> property.
        /// </summary>
        /// <param name="configuration">The configuration object for the Application Insights pipeline.</param>
        public void Initialize(TelemetryConfiguration configuration)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }

            this.client = new TelemetryClient(configuration);
            this.client.Context.GetInternalContext().SdkVersion = SdkVersionUtils.GetSdkVersion("dsl:");
            this.allDiagnosticListenersSubscription             = DiagnosticListener.AllListeners.Subscribe(this);
        }
Exemplo n.º 9
0
        /// <summary>
        /// Initializes the Target and perform instrumentationKey validation.
        /// </summary>
        /// <exception cref="NLogConfigurationException">Will throw when <see cref="InstrumentationKey"/> is not set.</exception>
        protected override void InitializeTarget()
        {
            base.InitializeTarget();
            this.telemetryClient = new TelemetryClient();
            if (!string.IsNullOrEmpty(this.InstrumentationKey))
            {
                this.telemetryClient.Context.InstrumentationKey = this.InstrumentationKey;
            }

            this.telemetryClient.Context.GetInternalContext().SdkVersion = SdkVersionUtils.GetSdkVersion("nlog:");
        }
Exemplo n.º 10
0
        /// <summary>
        /// Initializes the Appender and perform instrumentationKey validation.
        /// </summary>
        public override void ActivateOptions()
        {
            base.ActivateOptions();
            this.telemetryClient = new TelemetryClient();
            if (!string.IsNullOrEmpty(this.InstrumentationKey))
            {
                this.telemetryClient.Context.InstrumentationKey = this.InstrumentationKey;
            }

            this.telemetryClient.Context.GetInternalContext().SdkVersion = SdkVersionUtils.GetSdkVersion("log4net:");
        }
Exemplo n.º 11
0
        /// <summary>
        /// Initializes a new instance of the ApplicationInsightsTraceListener class.
        /// If empty or null instrumentation key is passed, it will fall back to the one specified in ApplicationInsights.config file.
        /// </summary>
        /// <param name="instrumentationKey">Instrumentation Key of your application.</param>
        public ApplicationInsightsTraceListener(string instrumentationKey)
        {
#pragma warning disable CS0618 // Type or member is obsolete
            this.TelemetryClient = new TelemetryClient();
#pragma warning restore CS0618 // Type or member is obsolete
            if (!string.IsNullOrEmpty(instrumentationKey))
            {
                this.TelemetryClient.Context.InstrumentationKey = instrumentationKey;
            }

            this.TelemetryClient.Context.GetInternalContext().SdkVersion = SdkVersionUtils.GetSdkVersion("sd:");
        }
        /// <summary>
        /// Initializes the Appender and perform instrumentationKey validation.
        /// </summary>
        public override void ActivateOptions()
        {
            base.ActivateOptions();
#pragma warning disable CS0618 // Type or member is obsolete
            this.telemetryClient = new TelemetryClient();
#pragma warning restore CS0618 // Type or member is obsolete
            if (!string.IsNullOrEmpty(this.InstrumentationKey))
            {
                this.telemetryClient.Context.InstrumentationKey = this.InstrumentationKey;
            }

            this.telemetryClient.Context.GetInternalContext().SdkVersion = SdkVersionUtils.GetSdkVersion("log4net:");
        }
Exemplo n.º 13
0
        /// <summary>
        /// Initializes the telemetry module.
        /// </summary>
        /// <param name="configuration">Telemetry configuration to use for initialization.</param>
        public void Initialize(TelemetryConfiguration configuration)
        {
            this.telemetryConfiguration = configuration;
            this.telemetryClient        = new TelemetryClient(configuration);
            this.telemetryClient.Context.GetInternalContext().SdkVersion = SdkVersionUtils.GetSdkVersion("web:");

            // Headers will be read-only in a classic iis pipeline
            // Exception System.PlatformNotSupportedException: This operation requires IIS integrated pipeline mode.
            if (HttpRuntime.UsingIntegratedPipeline && this.EnableChildRequestTrackingSuppression)
            {
                this.childRequestTrackingSuppressionModule = new ChildRequestTrackingSuppressionModule(maxRequestsTracked: this.ChildRequestTrackingInternalDictionarySize);
            }
        }
        /// <summary>
        /// Initializes the telemetry module and starts tracing EventSources specified via <see cref="Sources"/> property.
        /// </summary>
        /// <param name="configuration">Module configuration.</param>
        public void Initialize(TelemetryConfiguration configuration)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }

            this.client = new TelemetryClient(configuration);
            this.client.Context.GetInternalContext().SdkVersion = SdkVersionUtils.GetSdkVersion("evl:");

            if (this.Sources.Count == 0)
            {
                EventSourceListenerEventSource.Log.NoSourcesConfigured(nameof(EventSourceListener.EventSourceTelemetryModule));
                return;
            }

            // See OnEventSourceCreated() for the reason why we are locking on 'this' here.
            lock (this)
            {
                if (this.initialized)
                {
                    // Source listening requests might have changed between initializations. Let's start from a clean slate
                    foreach (EventSource eventSource in this.enabledEventSources)
                    {
                        this.DisableEvents(eventSource);
                    }
                    this.enabledEventSources.Clear();
                }

                try
                {
                    if (this.appDomainEventSources != null)
                    {
                        EventSource eventSource;
                        ConcurrentQueue <EventSource> futureIntializationSources = new ConcurrentQueue <EventSource>();

                        while (this.appDomainEventSources.TryDequeue(out eventSource))
                        {
                            this.EnableAsNecessary(eventSource);
                            futureIntializationSources.Enqueue(eventSource);
                        }

                        this.appDomainEventSources = futureIntializationSources;
                    }
                }
                finally
                {
                    this.initialized = true;
                }
            }
        }
        /// <summary />
        /// <param name="versionMoniker"></param>
        public static void ValidateSdkVersionString(string versionMoniker)
        {
            Assert.IsNotNull(versionMoniker);

            // Expected result example: "m-agg2:2.6.0-12552"

            const string expectedPrefix = "m-agg2:";

            string sdkRevisionComponentStr = versionMoniker.Substring(expectedPrefix.Length);
            string expectedVersion         = SdkVersionUtils.GetSdkVersion(String.Empty);

            Assert.IsTrue(versionMoniker.StartsWith(expectedPrefix), $"versionMoniker: \"{versionMoniker}\"; expectedPrefix: \"{expectedPrefix}\"");
            Assert.IsTrue(versionMoniker.EndsWith(expectedVersion), $"versionMoniker: \"{versionMoniker}\"; expectedVersion: \"{expectedVersion}\"");
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="ApplicationInsightsLoggerProvider"/> class.
        /// </summary>
        /// <param name="telemetryConfigurationOptions">The telemetry configuration options..</param>
        /// <param name="applicationInsightsLoggerOptions">The application insights logger options.</param>
        /// <exception cref="System.ArgumentNullException">
        /// telemetryConfiguration
        /// or
        /// loggingFilter
        /// or
        /// applicationInsightsLoggerOptions.
        /// </exception>
        public ApplicationInsightsLoggerProvider(
            IOptions <TelemetryConfiguration> telemetryConfigurationOptions,
            IOptions <ApplicationInsightsLoggerOptions> applicationInsightsLoggerOptions)
        {
            if (telemetryConfigurationOptions?.Value == null)
            {
                throw new ArgumentNullException(nameof(telemetryConfigurationOptions));
            }

            this.applicationInsightsLoggerOptions = applicationInsightsLoggerOptions?.Value ?? throw new ArgumentNullException(nameof(applicationInsightsLoggerOptions));

            this.telemetryClient = new TelemetryClient(telemetryConfigurationOptions.Value);
            this.telemetryClient.Context.GetInternalContext().SdkVersion = SdkVersionUtils.GetSdkVersion("il:");
        }
        private TelemetryClient GetTelemetryClient(TelemetryConfiguration sourceConfiguration)
        {
            this.channel.EndpointAddress = sourceConfiguration.TelemetryChannel.EndpointAddress;

            var newConfiguration = new TelemetryConfiguration
            {
                TelemetryChannel = this.channel,
            };

            CopyConfiguration(sourceConfiguration, newConfiguration);

            var telemetryClient = new TelemetryClient(newConfiguration);

            telemetryClient.Context.GetInternalContext().SdkVersion = SdkVersionUtils.GetSdkVersion("unhnd:");

            return(telemetryClient);
        }
Exemplo n.º 18
0
        /// <summary />
        /// <param name="versionMoniker"></param>
        public static void ValidateSdkVersionString(string versionMoniker)
        {
            Assert.IsNotNull(versionMoniker);

            // Expected result example: "m-agg2:2.6.0-12552"
#if NETCOREAPP // This constant is defined for all versions of NetCore https://docs.microsoft.com/en-us/dotnet/core/tutorials/libraries#how-to-multitarget
            const string expectedPrefix = "m-agg2c:";
#else
            const string expectedPrefix = "m-agg2:";
#endif

            string sdkRevisionComponentStr = versionMoniker.Substring(expectedPrefix.Length);
            string expectedVersion         = SdkVersionUtils.GetSdkVersion(String.Empty);

            Assert.IsTrue(versionMoniker.StartsWith(expectedPrefix), $"versionMoniker: \"{versionMoniker}\"; expectedPrefix: \"{expectedPrefix}\"");
            Assert.IsTrue(versionMoniker.EndsWith(expectedVersion), $"versionMoniker: \"{versionMoniker}\"; expectedVersion: \"{expectedVersion}\"");
        }
        /// <summary>
        /// Initializes the telemetry module.
        /// </summary>
        /// <param name="configuration">Telemetry configuration to use for initialization.</param>
        public void Initialize(TelemetryConfiguration configuration)
        {
            this.telemetryConfiguration = configuration ?? throw new ArgumentNullException(nameof(configuration));
            this.telemetryClient        = new TelemetryClient(configuration);
            this.telemetryClient.Context.GetInternalContext().SdkVersion = SdkVersionUtils.GetSdkVersion("web:");

            this.DisableTrackingProperties = configuration.EvaluateExperimentalFeature(Microsoft.ApplicationInsights.Common.Internal.ExperimentalConstants.DeferRequestTrackingProperties);
            if (this.DisableTrackingProperties)
            {
                configuration.DefaultTelemetrySink.TelemetryProcessorChainBuilder.Use(next => new PostSamplingTelemetryProcessor(next));
                configuration.DefaultTelemetrySink.TelemetryProcessorChainBuilder.Build();
            }

            // Headers will be read-only in a classic iis pipeline
            // Exception System.PlatformNotSupportedException: This operation requires IIS integrated pipeline mode.
            if (HttpRuntime.UsingIntegratedPipeline && this.EnableChildRequestTrackingSuppression)
            {
                this.childRequestTrackingSuppressionModule = new ChildRequestTrackingSuppressionModule(maxRequestsTracked: this.ChildRequestTrackingInternalDictionarySize);
            }
        }
Exemplo n.º 20
0
        /// <summary>
        /// Initializes the telemetry module and starts tracing DiagnosticSources specified via the <see cref="Sources"/> property.
        /// </summary>
        /// <param name="configuration">The configuration object for the Application Insights pipeline.</param>
        public void Initialize(TelemetryConfiguration configuration)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }

            var telemetryClient = new TelemetryClient(configuration);

            telemetryClient.Context.GetInternalContext().SdkVersion = SdkVersionUtils.GetSdkVersion("dsl:");

            this.client = telemetryClient;

            // Protect against multiple subscriptions if Initialize is called twice
            if (this.allDiagnosticListenersSubscription == null)
            {
                var subscription = DiagnosticListener.AllListeners.Subscribe(this);
                if (Interlocked.CompareExchange(ref this.allDiagnosticListenersSubscription, subscription, null) != null)
                {
                    subscription.Dispose();
                }
            }
        }
Exemplo n.º 21
0
 /// <summary>
 /// Creates an instance of the <see cref="WebApiExceptionLogger"/> using the <see cref="TelemetryClient"/> passed in.
 /// </summary>
 public WebApiExceptionLogger(TelemetryClient telemetryClient)
 {
     _telemetryClient = telemetryClient ?? new TelemetryClient();
     _sdkVersion      = SdkVersionUtils.GetSdkVersion("owin:");
 }
Exemplo n.º 22
0
 /// <summary>
 /// Initializes the telemetry module.
 /// </summary>
 /// <param name="configuration">Telemetry configuration to use for initialization.</param>
 public void Initialize(TelemetryConfiguration configuration)
 {
     if (this.EnableMvcAndWebApiExceptionAutoTracking)
     {
         if (!this.isInitialized)
         {
             lock (this.lockObject)
             {
                 if (!this.isInitialized)
                 {
                     this.telemetryClient = new TelemetryClient(configuration);
                     this.telemetryClient.Context.GetInternalContext().SdkVersion = SdkVersionUtils.GetSdkVersion("web:");
                     ExceptionHandlersInjector.Inject(this.telemetryClient);
                     this.isInitialized = true;
                 }
             }
         }
     }
 }
Exemplo n.º 23
0
        /// <summary>
        /// Initializes the telemetry module.
        /// </summary>
        /// <param name="configuration">Telemetry Configuration used for creating TelemetryClient for sending exception statistics to Application Insights.</param>
        public void Initialize(TelemetryConfiguration configuration)
        {
            // Core SDK creates 1 instance of a module but calls Initialize multiple times
            if (!this.isInitialized)
            {
                lock (this.lockObject)
                {
                    if (!this.isInitialized)
                    {
                        this.telemetryClient = new TelemetryClient(configuration);
                        this.telemetryClient.Context.GetInternalContext().SdkVersion = SdkVersionUtils.GetSdkVersion("exstat:");

                        this.MetricManager = new MetricManager(this.telemetryClient, configuration);

                        this.registerAction(this.CalculateStatistics);

                        this.isInitialized = true;
                    }
                }
            }
        }
Exemplo n.º 24
0
        public void Initialize(ITelemetry telemetry)
        {
            string instrumentationKey = this.Context.InstrumentationKey;

            if (string.IsNullOrEmpty(instrumentationKey))
            {
                instrumentationKey = this.configuration.InstrumentationKey;
            }

            var telemetryWithProperties = telemetry as ISupportProperties;

            if (telemetryWithProperties != null)
            {
                if ((this.configuration.TelemetryChannel != null) && (this.configuration.TelemetryChannel.DeveloperMode.HasValue && this.configuration.TelemetryChannel.DeveloperMode.Value))
                {
                    if (!telemetryWithProperties.Properties.ContainsKey("DeveloperMode"))
                    {
                        telemetryWithProperties.Properties.Add("DeveloperMode", "true");
                    }
                }

                Utils.CopyDictionary(this.Context.Properties, telemetryWithProperties.Properties);
            }

            telemetry.Context.Initialize(this.Context, instrumentationKey);
            foreach (ITelemetryInitializer initializer in this.configuration.TelemetryInitializers)
            {
                try
                {
                    initializer.Initialize(telemetry);
                }
                catch (Exception exception)
                {
                    CoreEventSource.Log.LogError(string.Format(
                                                     CultureInfo.InvariantCulture,
                                                     "Exception while initializing {0}, exception message - {1}",
                                                     initializer.GetType().FullName,
                                                     exception));
                }
            }

            if (telemetry.Timestamp == default(DateTimeOffset))
            {
                telemetry.Timestamp = DateTimeOffset.UtcNow;
            }

            // Currently backend requires SDK version to comply "name: version"
            if (string.IsNullOrEmpty(telemetry.Context.Internal.SdkVersion))
            {
                var version = LazyInitializer.EnsureInitialized(ref this.sdkVersion, () => SdkVersionUtils.GetSdkVersion(VersionPrefix));
                telemetry.Context.Internal.SdkVersion = version;
            }

            // set NodeName to the machine name if it's not initialized yet, if RoleInstance is also not set then we send only RoleInstance
            if (string.IsNullOrEmpty(telemetry.Context.Internal.NodeName) && !string.IsNullOrEmpty(telemetry.Context.Cloud.RoleInstance))
            {
                telemetry.Context.Internal.NodeName = PlatformSingleton.Current.GetMachineName();
            }

            // set RoleInstance to the machine name if it's not initialized yet
            if (string.IsNullOrEmpty(telemetry.Context.Cloud.RoleInstance))
            {
                telemetry.Context.Cloud.RoleInstance = PlatformSingleton.Current.GetMachineName();
            }
        }
        /// <summary>
        /// Initializes the telemetry module.
        /// </summary>
        /// <param name="configuration">Telemetry Configuration used for creating TelemetryClient for sending exceptions to ApplicationInsights.</param>
        public void Initialize(TelemetryConfiguration configuration)
        {
            // Core SDK creates 1 instance of a module but calls Initialize multiple times
            if (!this.isInitialized)
            {
                lock (this.lockObject)
                {
                    if (!this.isInitialized)
                    {
                        this.isInitialized = true;

                        this.telemetryClient = new TelemetryClient(configuration);
                        this.telemetryClient.Context.GetInternalContext().SdkVersion = SdkVersionUtils.GetSdkVersion("unobs:");

                        this.registerAction(this.TaskSchedulerOnUnobservedTaskException);
                    }
                }
            }
        }
Exemplo n.º 26
0
        /// <summary>
        /// Initializes the telemetry module and starts tracing ETW events specified via <see cref="Sources"/> property.
        /// </summary>
        /// <param name="configuration">Module configuration.</param>
        public void Initialize(TelemetryConfiguration configuration)
        {
            string errorMessage;

            if (configuration == null)
            {
                errorMessage = string.Format(CultureInfo.InvariantCulture, "Argument {0} is required. The initialization is terminated.", nameof(configuration));
                EventSourceListenerEventSource.Log.ModuleInitializationFailed(
                    nameof(EtwTelemetryModule),
                    errorMessage);
                return;
            }

            if (this.isDisposed)
            {
                errorMessage = "Can't initialize a module that is disposed. The initialization is terminated.";
                EventSourceListenerEventSource.Log.ModuleInitializationFailed(
                    nameof(EtwTelemetryModule),
                    errorMessage);
                return;
            }

            lock (this.lockObject)
            {
                this.client = new TelemetryClient(configuration);

                // sdkVersionIdentifier will be used in telemtry entry as a identifier for the sender.
                // The value will look like: etw:x.x.x-x
                const string SdkVersionIdentifier = "etw:";
                this.client.Context.GetInternalContext().SdkVersion = SdkVersionUtils.GetSdkVersion(SdkVersionIdentifier);

                if (this.isInitialized)
                {
                    this.DisableProviders();
                    this.enabledProviderIds.Clear();
                    this.enabledProviderNames.Clear();
                }

                if (this.Sources.Count == 0)
                {
                    EventSourceListenerEventSource.Log.NoSourcesConfigured(moduleName: nameof(EtwTelemetryModule));
                    this.isInitialized = false;
                    return;
                }

                if (this.traceEventSession == null)
                {
                    this.traceEventSession = this.traceEventSessionFactory();
                }

                this.EnableProviders();

                if (!this.isInitialized)
                {
                    try
                    {
                        // Start the trace session
                        if (this.traceEventSession != null && this.traceEventSession.Source != null && this.traceEventSession.Source.Dynamic != null)
                        {
                            this.traceEventSession.Source.Dynamic.All += this.OnEvent;
                            Task.Factory.StartNew(
                                () =>
                            {
                                this.traceEventSession.Source.Process();
                                this.traceEventSession.Source.Dynamic.All -= this.OnEvent;
                                this.isInitialized = false;
                            },
                                TaskCreationOptions.LongRunning);
                        }
                    }
                    finally
                    {
                        this.isInitialized = true;
                    }
                }
            }
        }
        /// <summary>
        /// Initializes the telemetry module and starts tracing EventSources specified via <see cref="Sources"/> property.
        /// </summary>
        /// <param name="configuration">Module configuration.</param>
        public void Initialize(TelemetryConfiguration configuration)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }

            this.client = new TelemetryClient(configuration);
            this.client.Context.GetInternalContext().SdkVersion = SdkVersionUtils.GetSdkVersion("evl:");

            if (this.Sources.Count == 0)
            {
                EventSourceListenerEventSource.Log.NoSourcesConfigured(nameof(EventSourceListener.EventSourceTelemetryModule));
                // Continue--we need to be prepared for handling disabled sources.
            }

            try
            {
                if (this.initialized)
                {
                    // Source listening requests might have changed between initializations. Let's start from a clean slate
                    EventSource enabledEventSource = null;
                    while (this.enabledEventSources.TryDequeue(out enabledEventSource))
                    {
                        this.DisableEvents(enabledEventSource);
                    }
                }

                // Special case: because of .NET bug https://github.com/dotnet/coreclr/issues/14434, using Microsoft-ApplicationInsights-Data will result in infinite loop.
                // So we will disable it by default, unless there is explicit configuration for this EventSource.
                bool hasExplicitConfigForAiDataSource =
                    this.Sources.Any(req => req.Name?.StartsWith(AppInsightsDataEventSource, StringComparison.Ordinal) ?? false) ||
                    this.DisabledSources.Any(req => req.Name?.StartsWith(AppInsightsDataEventSource, StringComparison.Ordinal) ?? false);
                if (!hasExplicitConfigForAiDataSource)
                {
                    this.DisabledSources.Add(new DisableEventSourceRequest {
                        Name = AppInsightsDataEventSource
                    });
                }

                // Set the initialized flag now to ensure that we do not miss any sources that came online as we are executing the initialization
                // (OnEventSourceCreated() might have been called on a separate thread). Worst case we will attempt to enable the same source twice
                // (with same settings), but that is OK, as the semantics of EnableEvents() is really "update what is being tracked", so it is fine
                // to call it multiple times for the same source.
                this.initialized = true;

                if (this.appDomainEventSources != null)
                {
                    // Decide if there is disable event source listening requests
                    if (this.DisabledSources.Any())
                    {
                        this.enabledOrDisabledEventSourceTestResultCache = new ConcurrentDictionary <string, bool>();
                        this.eventWrittenHandlerPicker = this.OnEventWrittenIfSourceNotDisabled;
                    }
                    else
                    {
                        this.eventWrittenHandlerPicker = this.onEventWrittenHandler;
                    }

                    // Enumeration over concurrent queue is thread-safe.
                    foreach (EventSource eventSourceToEnable in this.appDomainEventSources)
                    {
                        this.EnableAsNecessary(eventSourceToEnable);
                    }
                }
            }
            finally
            {
                // No matter what problems we encounter with enabling EventSources, we should note that we have been initialized.
                this.initialized = true;
            }
        }
Exemplo n.º 28
0
 /// <summary>
 /// Initializes the telemetry module.
 /// </summary>
 /// <param name="configuration">Telemetry configuration to use for initialization.</param>
 public void Initialize(TelemetryConfiguration configuration)
 {
     this.telemetryClient = new TelemetryClient(configuration);
     this.telemetryClient.Context.GetInternalContext().SdkVersion = SdkVersionUtils.GetSdkVersion("web:");
 }
Exemplo n.º 29
0
        /// <summary>
        /// Initialize method is called after all configuration properties have been loaded from the configuration.
        /// </summary>
        public void Initialize(TelemetryConfiguration configuration)
        {
            if (!this.isInitialized)
            {
                lock (this.lockObject)
                {
                    if (!this.isInitialized)
                    {
                        PerformanceCollectorEventSource.Log.ModuleIsBeingInitializedEvent(
                            string.Format(
                                CultureInfo.InvariantCulture,
                                "Custom counters count: '{0}'",
                                Counters?.Count ?? 0));

                        if (configuration == null)
                        {
                            throw new ArgumentNullException(nameof(configuration));
                        }

                        if (!this.defaultCountersInitialized)
                        {
                            // The following are the counters support in all cases.
                            this.DefaultCounters.Add(new PerformanceCounterCollectionRequest(@"\Process(??APP_WIN32_PROC??)\% Processor Time", @"\Process(??APP_WIN32_PROC??)\% Processor Time"));
                            this.DefaultCounters.Add(new PerformanceCounterCollectionRequest(@"\Process(??APP_WIN32_PROC??)\% Processor Time Normalized", @"\Process(??APP_WIN32_PROC??)\% Processor Time Normalized"));
                            this.DefaultCounters.Add(new PerformanceCounterCollectionRequest(@"\Process(??APP_WIN32_PROC??)\Private Bytes", @"\Process(??APP_WIN32_PROC??)\Private Bytes"));

#if NET45                   // The following are Asp.Net specific counters.
                            this.DefaultCounters.Add(new PerformanceCounterCollectionRequest(@"\ASP.NET Applications(??APP_W3SVC_PROC??)\Requests/Sec", @"\ASP.NET Applications(??APP_W3SVC_PROC??)\Requests/Sec"));
                            this.DefaultCounters.Add(new PerformanceCounterCollectionRequest(@"\.NET CLR Exceptions(??APP_CLR_PROC??)\# of Exceps Thrown / sec", @"\.NET CLR Exceptions(??APP_CLR_PROC??)\# of Exceps Thrown / sec"));
                            this.DefaultCounters.Add(new PerformanceCounterCollectionRequest(@"\ASP.NET Applications(??APP_W3SVC_PROC??)\Request Execution Time", @"\ASP.NET Applications(??APP_W3SVC_PROC??)\Request Execution Time"));
                            this.DefaultCounters.Add(new PerformanceCounterCollectionRequest(@"\ASP.NET Applications(??APP_W3SVC_PROC??)\Requests In Application Queue", @"\ASP.NET Applications(??APP_W3SVC_PROC??)\Requests In Application Queue"));
#endif

                            if (this.collector.GetType().Name.Equals("WebAppPerformanceCollector", StringComparison.OrdinalIgnoreCase) || this.collector.GetType().Name.Equals("StandardPerformanceCollector", StringComparison.OrdinalIgnoreCase))
                            {
                                // The systemwide Memory counter is enabled in WebApps.
                                this.DefaultCounters.Add(new PerformanceCounterCollectionRequest(@"\Memory\Available Bytes", @"\Memory\Available Bytes"));
                                this.DefaultCounters.Add(new PerformanceCounterCollectionRequest(@"\Process(??APP_WIN32_PROC??)\IO Data Bytes/sec", @"\Process(??APP_WIN32_PROC??)\IO Data Bytes/sec"));
                            }

                            if (this.collector.GetType().Name.Equals("StandardPerformanceCollector", StringComparison.OrdinalIgnoreCase))
                            {
                                // Only time total CPU counter is available is if we are using StandardPerformanceCollector.
                                this.DefaultCounters.Add(new PerformanceCounterCollectionRequest(@"\Processor(_Total)\% Processor Time", @"\Processor(_Total)\% Processor Time"));
                            }
                        }

                        if (!this.EnableIISExpressPerformanceCounters && IsRunningUnderIisExpress())
                        {
                            PerformanceCollectorEventSource.Log.RunningUnderIisExpress();
                            return;
                        }

                        this.telemetryConfiguration = configuration;
                        this.client = new TelemetryClient(configuration);
                        this.client.Context.GetInternalContext().SdkVersion = SdkVersionUtils.GetSdkVersion(PerformanceCounterUtility.SDKVersionPrefix());

                        this.lastRefreshTimestamp = DateTime.MinValue;

                        this.timer = new Timer(this.TimerCallback);

                        // schedule the first tick
                        this.timer.ScheduleNextTick(this.collectionPeriod);
                        this.isInitialized = true;
                    }
                }
            }
        }
        private void InitializeServiceClient(TelemetryConfiguration configuration)
        {
            if (this.ServiceClient != null)
            {
                // service client has been passed through a constructor, we don't need to do anything
                return;
            }

            Uri serviceEndpointUri;

            if (string.IsNullOrWhiteSpace(this.QuickPulseServiceEndpoint))
            {
                // endpoint is not explicitly specified, use the Endpoint from the TelemetryConfiguration (ex: https://rt.services.visualstudio.com/QuickPulseService.svc)
                serviceEndpointUri = new Uri(configuration.EndpointContainer.Live, "QuickPulseService.svc");
            }
            else
            {
                // endpoint appears to have been specified in configuration, try using it
                try
                {
                    serviceEndpointUri = new Uri(this.QuickPulseServiceEndpoint);
                }
                catch (Exception e)
                {
                    throw new ArgumentException(
                              string.Format(
                                  CultureInfo.InvariantCulture,
                                  "Error initializing QuickPulse module. QPS endpoint is not a correct URI: '{0}'",
                                  this.QuickPulseServiceEndpoint),
                              e);
                }
            }

            // create the default production implementation of the service client with the best service endpoint we could get
            string instanceName    = GetInstanceName(configuration);
            string streamId        = GetStreamId();
            var    assemblyVersion = SdkVersionUtils.GetSdkVersion(null);
            bool   isWebApp        = PerformanceCounterUtility.IsWebAppRunningInAzure();
            int?   processorCount  = PerformanceCounterUtility.GetProcessorCount();

            this.ServiceClient = new QuickPulseServiceClient(
                serviceEndpointUri,
                instanceName,
                streamId,
                ServerId,
                assemblyVersion,
                this.timeProvider,
                isWebApp,
                processorCount ?? 0);

            // TelemetryConfigurationFactory will initialize Modules after Processors. Need to update the processor with the correct service endpoint.
            foreach (var processor in this.TelemetryProcessors)
            {
                processor.ServiceEndpoint = serviceEndpointUri;
            }

            QuickPulseEventSource.Log.TroubleshootingMessageEvent(
                string.Format(
                    CultureInfo.InvariantCulture,
                    "Service client initialized. Endpoint: '{0}', instance name: '{1}', assembly version: '{2}'",
                    serviceEndpointUri,
                    instanceName,
                    assemblyVersion));
        }