Ejemplo n.º 1
0
        public void LogEvent(PythonLogEvent logEvent, object argument) {
            var session = _session.Value;
            // No session is not a fatal error
            if (session == null) {
                return;
            }

            // Never send events when users have not opted in.
            if (!session.IsOptedIn) {
                return;
            }

            // Certain events are not collected
            switch (logEvent) {
                case PythonLogEvent.AnalysisWarning:
                case PythonLogEvent.AnalysisOperationFailed:
                case PythonLogEvent.AnalysisOperationCancelled:
                case PythonLogEvent.AnalysisExitedAbnormally:
                    return;
            }

            var evt = new TelemetryEvent(EventPrefix + logEvent.ToString());
            var props = PythonToolsLoggerData.AsDictionary(argument);
            if (props != null) {
                foreach (var kv in props) {
                    evt.Properties[PropertyPrefix + kv.Key] = kv.Value;
                }
            } else if (argument != null) {
                evt.Properties[PropertyPrefix + "Value"] = argument;
            }

            session.PostEvent(evt);
        }
 public void ReportEvent(TelemetryEvent telemetryEvent)
 {
     Action logTelemetry;
     if (this.eventLoggerMap.TryGetValue(telemetryEvent, out logTelemetry))
     {
         logTelemetry();
     }
     else
     {
         Debug.Fail("Unsupported event: " + telemetryEvent);
     }
 }
Ejemplo n.º 3
0
        private void OnTelemetryEvent(TelemetryEvent msg)
        {
            switch (msg.Category)
            {
            case TelemetryCategory.Share:
                shareCounter.WithLabels(msg.PoolId).Inc();
                break;

            case TelemetryCategory.BtStream:
                btStreamLatencySummary.WithLabels(msg.PoolId).Observe(msg.Elapsed.TotalMilliseconds);
                break;

            case TelemetryCategory.RpcRequest:
                rpcRequestDurationSummary.WithLabels(msg.PoolId, msg.Info).Observe(msg.Elapsed.TotalMilliseconds);
                break;
            }
        }
        public void Track(TelemetryEvent tEvent)
        {
            if (!IsEnabled)
            {
                return;
            }

            var configuration = new Configuration()
            {
                ApplicationId = ApplicationId,
                BaseAddress   = BaseAddress,
                Client        = client,
                ConfigFolder  = ConfigFolder
            };

            Provider.Track(configuration, tEvent);
        }
Ejemplo n.º 5
0
        public void Enqueue_DataNull()
        {
            // arrange
            IMemoryBuffer <EventData> buffer = new Mock <IMemoryBuffer <EventData> >().Object;
            ITransmissionBuffer <EventData, EventDataBatch> aggregator = Mock.Of <ITransmissionBuffer <EventData, EventDataBatch> >();
            ITransmissionSender <EventDataBatch>            sender     = new Mock <ITransmissionSender <EventDataBatch> >().Object;
            ITransmissionStorage <EventData> storage     = new Mock <ITransmissionStorage <EventData> >().Object;
            ITelemetryEventTransmitter       transmitter = new EventHubTransmitter(
                buffer, aggregator, sender, storage);
            TelemetryEvent data = null;

            // act
            Action verify = () => transmitter.Enqueue(data);

            // assert
            Assert.Throws <ArgumentNullException>("data", verify);
        }
Ejemplo n.º 6
0
        public void Enqueue_TransmissionFlow()
        {
            // assert
            ManualResetEventSlim resetEvent          = new ManualResetEventSlim();
            Mock <IMemoryBuffer <EventData> > buffer = new Mock <IMemoryBuffer <EventData> >();
            Mock <ITransmissionBuffer <EventData, EventDataBatch> > aggregator = new Mock <ITransmissionBuffer <EventData, EventDataBatch> >();
            Mock <ITransmissionSender <EventDataBatch> >            sender     = new Mock <ITransmissionSender <EventDataBatch> >();
            Mock <ITransmissionStorage <EventData> > storage     = new Mock <ITransmissionStorage <EventData> >();
            ConcurrentQueue <EventDataBatch>         bufferQueue = new ConcurrentQueue <EventDataBatch>();

            buffer
            .Setup(t => t.Enqueue(It.IsAny <EventData>()))
            .Callback((EventData d) => bufferQueue.Enqueue(EventHubsModelFactory.EventDataBatch(1, new[] { d })));
            aggregator
            .Setup(t => t.Dequeue(It.IsAny <CancellationToken>()))
            .Returns(() =>
            {
                int count = 0;
                List <EventDataBatch> results = new List <EventDataBatch>();

                while (bufferQueue.TryDequeue(out EventDataBatch d) && count < 10)
                {
                    results.Add(d);
                    count++;
                }

                return(results.ToAsyncEnumerable());
            });
            sender
            .Setup(t => t.SendAsync(It.IsAny <IAsyncEnumerable <EventDataBatch> >(), It.IsAny <CancellationToken>()))
            .Callback(() => resetEvent.Set());

            ITelemetryEventTransmitter transmitter = new EventHubTransmitter(
                buffer.Object, aggregator.Object, sender.Object, storage.Object);
            TelemetryEvent data = new TelemetryEvent();

            // act
            transmitter.Enqueue(data);

            // arrange
            resetEvent.Wait(TimeSpan.FromSeconds(5));

            sender.Verify(s => s.SendAsync(
                              It.IsAny <IAsyncEnumerable <EventDataBatch> >(),
                              It.IsAny <CancellationToken>()), Times.Once);
        }
Ejemplo n.º 7
0
 /// <summary>
 /// Records event with parameters
 /// </summary>
 public void RecordEvent(string eventName, object parameters = null) {
     if (this.IsEnabled) {
         TelemetryEvent telemetryEvent = new TelemetryEvent(eventName);
         if (parameters != null) {
             var stringParameter = parameters as string;
             if (stringParameter != null) {
                 telemetryEvent.Properties["Value"] = stringParameter;
             } else {
                 IDictionary<string, object> dict = DictionaryExtension.FromAnonymousObject(parameters);
                 foreach (KeyValuePair<string, object> kvp in dict) {
                     telemetryEvent.Properties[kvp.Key] = kvp.Value;
                 }
             }
         }
         _session.PostEvent(telemetryEvent);
     }
 }
Ejemplo n.º 8
0
        public void ReportApiUsage(HashSet <ISymbol> symbols, Guid solutionSessionId, Guid projectGuid)
        {
            const string EventName             = "vs/compilers/api";
            const string ApiPropertyName       = "vs.compilers.api.pii";
            const string ProjectIdPropertyName = "vs.solution.project.projectid";
            const string SessionIdPropertyName = "vs.solution.solutionsessionid";

            var groupByAssembly = symbols.GroupBy(symbol => symbol.ContainingAssembly);

            var apiPerAssembly = groupByAssembly.Select(assemblyGroup => new
            {
                // mark all string as PII (customer data)
                AssemblyName    = new TelemetryPiiProperty(assemblyGroup.Key.Identity.Name),
                AssemblyVersion = assemblyGroup.Key.Identity.Version.ToString(),
                Namespaces      = assemblyGroup.GroupBy(symbol => symbol.ContainingNamespace)
                                  .Select(namespaceGroup =>
                {
                    var namespaceName = namespaceGroup.Key?.ToString() ?? string.Empty;

                    return(new
                    {
                        Namespace = new TelemetryPiiProperty(namespaceName),
                        Symbols = namespaceGroup.Select(symbol => symbol.GetDocumentationCommentId())
                                  .Where(id => id != null)
                                  .Select(id => new TelemetryPiiProperty(id))
                    });
                })
            });

            // use telemetry API directly rather than Logger abstraction for PII data
            var telemetryEvent = new TelemetryEvent(EventName);

            telemetryEvent.Properties[ApiPropertyName]       = new TelemetryComplexProperty(apiPerAssembly);
            telemetryEvent.Properties[SessionIdPropertyName] = new TelemetryPiiProperty(solutionSessionId.ToString("B"));
            telemetryEvent.Properties[ProjectIdPropertyName] = new TelemetryPiiProperty(projectGuid.ToString("B"));

            try
            {
                CurrentSession?.PostEvent(telemetryEvent);
            }
            catch
            {
                // no-op
            }
        }
Ejemplo n.º 9
0
        public void TelemetryEventObjectSetsPropertiesToExpectedValues()
        {
            string   eventName     = "AnyEvent";
            Guid     correlationId = Guid.NewGuid();
            DateTime timestamp     = DateTime.Now;
            string   context       = "Any context";

            TelemetryEvent <string> telemetry = new TelemetryEvent <string>(
                eventName,
                correlationId,
                timestamp,
                context);

            Assert.AreEqual(eventName, telemetry.EventName);
            Assert.AreEqual(correlationId, telemetry.CorrelationId);
            Assert.AreEqual(timestamp, telemetry.Timestamp);
            Assert.AreEqual(context, telemetry.Context);
        }
Ejemplo n.º 10
0
        internal ConsoleApp(string[] args, Assembly assembly, IContainer container)
        {
            _args           = args;
            _container      = container;
            _telemetryEvent = new TelemetryEvent();
            // TypeAttributePair is just a typed tuple of an IAction type and one of its action attribute.
            _actionAttributes = assembly
                                .GetTypes()
                                .Where(t => typeof(IAction).IsAssignableFrom(t) && !t.IsAbstract)
                                .Select(type => type.GetCustomAttributes <ActionAttribute>().Select(a => new TypeAttributePair {
                Type = type, Attribute = a
            }))
                                .SelectMany(i => i);

            // Check if there is a --prefix or --script-root and update CurrentDirectory
            UpdateCurrentDirectory(args);
            GlobalCoreToolsSettings.Init(container.Resolve <ISecretsManager>(), args);
        }
Ejemplo n.º 11
0
        public void LogEvent(PythonLogEvent logEvent, object argument)
        {
            var session = _session.Value;

            // No session is not a fatal error
            if (session == null)
            {
                return;
            }

            // Never send events when users have not opted in.
            if (!session.IsOptedIn)
            {
                return;
            }

            // Certain events are not collected
            switch (logEvent)
            {
            case PythonLogEvent.AnalysisWarning:
            case PythonLogEvent.AnalysisOperationFailed:
            case PythonLogEvent.AnalysisOperationCancelled:
            case PythonLogEvent.AnalysisExitedAbnormally:
                return;
            }

            var evt   = new TelemetryEvent(EventPrefix + logEvent.ToString());
            var props = PythonToolsLoggerData.AsDictionary(argument);

            if (props != null)
            {
                foreach (var kv in props)
                {
                    evt.Properties[PropertyPrefix + kv.Key] = kv.Value;
                }
            }
            else if (argument != null)
            {
                evt.Properties[PropertyPrefix + "Value"] = argument;
            }

            session.PostEvent(evt);
        }
        public void RestoreTelemetryService_EmitRestoreEvent_OperationSucceed(bool forceRestore, RestoreOperationSource source, NuGetOperationStatus status)
        {
            // Arrange
            var            telemetrySession   = new Mock <ITelemetrySession>();
            TelemetryEvent lastTelemetryEvent = null;

            telemetrySession
            .Setup(x => x.PostEvent(It.IsAny <TelemetryEvent>()))
            .Callback <TelemetryEvent>(x => lastTelemetryEvent = x);

            var noopProjectsCount = 0;

            if (status == NuGetOperationStatus.NoOp)
            {
                noopProjectsCount = 1;
            }

            var stausMessage = status == NuGetOperationStatus.Failed ? "Operation Failed" : string.Empty;

            var operationId = Guid.NewGuid().ToString();

            var restoreTelemetryData = new RestoreTelemetryEvent(
                operationId,
                projectIds: new[] { Guid.NewGuid().ToString() },
                forceRestore: forceRestore,
                source: source,
                startTime: DateTimeOffset.Now.AddSeconds(-3),
                status: status,
                packageCount: 2,
                noOpProjectsCount: noopProjectsCount,
                upToDateProjectsCount: 5,
                endTime: DateTimeOffset.Now,
                duration: 2.10,
                isSolutionLoadRestore: true,
                new IntervalTracker("Activity"));
            var service = new NuGetVSTelemetryService(telemetrySession.Object);

            // Act
            service.EmitTelemetryEvent(restoreTelemetryData);

            // Assert
            VerifyTelemetryEventData(operationId, restoreTelemetryData, lastTelemetryEvent);
        }
Ejemplo n.º 13
0
        public void EmitTelemetryEvent(Guid parentId)
        {
            var telemetryEvent = new TelemetryEvent(PackagePreFetcherInformation);

            telemetryEvent["DownloadStartTime"] = _downloadStartTime;
            telemetryEvent["PackageFetchTime"]  = _packageFetchTime;
            telemetryEvent["TaskReturnTime"]    = _taskReturnTime;

            var packageId = CryptoHashUtility.GenerateUniqueToken(Package.ToString());

            telemetryEvent.AddPiiData("PackageId", Package.ToString());

            if (parentId != Guid.Empty)
            {
                telemetryEvent["ParentId"] = parentId.ToString();
            }

            TelemetryActivity.EmitTelemetryEvent(telemetryEvent);
        }
        public void NuGetTelemetryService_EmitProjectDependencyStatistics()
        {
            // Arrange
            var            telemetrySession   = new Mock <ITelemetrySession>();
            TelemetryEvent lastTelemetryEvent = null;

            telemetrySession
            .Setup(x => x.PostEvent(It.IsAny <TelemetryEvent>()))
            .Callback <TelemetryEvent>(x => lastTelemetryEvent = x);

            var projectInformation = new ProjectDependencyStatistics(
                "3.5.0-beta2",
                new Guid("15e9591f-9391-4ddf-a246-ca9e0351277d"),
                3);
            var target = new NuGetTelemetryService(telemetrySession.Object);

            // Act
            target.EmitProjectDependencyStatistics(projectInformation);

            // Assert
            telemetrySession.Verify(x => x.PostEvent(It.IsAny <TelemetryEvent>()), Times.Once);
            Assert.NotNull(lastTelemetryEvent);
            Assert.Equal("VS/NuGet/DependencyStatistics", lastTelemetryEvent.Name);
            Assert.Equal(3, lastTelemetryEvent.Properties.Count);

            object nuGetVersion;

            Assert.True(lastTelemetryEvent.Properties.TryGetValue("VS.NuGet.NuGetVersion", out nuGetVersion));
            Assert.IsType <string>(nuGetVersion);
            Assert.Equal(projectInformation.NuGetVersion, nuGetVersion);

            object projectId;

            Assert.True(lastTelemetryEvent.Properties.TryGetValue("VS.NuGet.ProjectId", out projectId));
            Assert.IsType <string>(projectId);
            Assert.Equal(projectInformation.ProjectId.ToString(), projectId);

            object installedPackageCount;

            Assert.True(lastTelemetryEvent.Properties.TryGetValue("VS.NuGet.InstalledPackageCount", out installedPackageCount));
            Assert.IsType <int>(installedPackageCount);
            Assert.Equal(projectInformation.InstalledPackageCount, installedPackageCount);
        }
Ejemplo n.º 15
0
        /// <summary>
        /// If addDateTime is sppecified Year, Month, Day properties are added. If time portion is not 00:00:00.000 then also Hour is added.
        /// </summary>
        private void LogEvent(TelemetryEvent eventName, IDictionary <string, string> properties)
        {
            if (AppConfig.Logging.LogEvents)
            {
                var et = new EventTelemetry(eventName.Title());

                foreach (var entry in properties)
                {
                    et.Properties.Add(entry.Key, entry.Value);
                }

                et.Sequence = eventName.Sequence();

                Client.TrackEvent(et);
#if DEBUG
                Client.Flush();
#endif
            }
        }
Ejemplo n.º 16
0
        public void Enqueue_TransmissionFlow()
        {
            // assert
            ManualResetEventSlim resetEvent = new ManualResetEventSlim();
            Mock <ITransmissionBuffer <EventData> > buffer      = new Mock <ITransmissionBuffer <EventData> >();
            Mock <ITransmissionSender <EventData> > sender      = new Mock <ITransmissionSender <EventData> >();
            ConcurrentQueue <EventData>             bufferQueue = new ConcurrentQueue <EventData>();

            buffer
            .Setup(t => t.EnqueueAsync(It.IsAny <EventData>(), It.IsAny <CancellationToken>()))
            .Callback((EventData d, CancellationToken t) => bufferQueue.Enqueue(d));
            buffer
            .Setup(t => t.DequeueAsync(It.IsAny <CancellationToken>()))
            .Returns(() =>
            {
                int count = 0;
                List <EventData> results = new List <EventData>();

                while (bufferQueue.TryDequeue(out EventData d) && count < 10)
                {
                    results.Add(d);
                    count++;
                }

                return(Task.FromResult(results.AsEnumerable()));
            });
            sender
            .Setup(t => t.SendAsync(It.IsAny <IEnumerable <EventData> >(), It.IsAny <CancellationToken>()))
            .Callback(() => resetEvent.Set());

            ITelemetryEventTransmitter transmitter = new EventHubTransmitter(buffer.Object, sender.Object);
            TelemetryEvent             data        = new TelemetryEvent();

            // act
            transmitter.Enqueue(data);

            // arrange
            resetEvent.Wait(TimeSpan.FromSeconds(5));

            sender.Verify(s => s.SendAsync(
                              It.Is((IEnumerable <EventData> d) => d.Count() == 1),
                              It.IsAny <CancellationToken>()), Times.Once);
        }
Ejemplo n.º 17
0
        private void OnAnalysisComplete(object sender, AnalysisCompleteEventArgs e)
        {
            if (e.MillisecondsElapsed < 500)
            {
                return;
            }
            var telemetry = _services.GetService <ITelemetryService>();

            if (telemetry == null)
            {
                return;
            }

            try {
                double privateMB;
                double peakPagedMB;
                double workingMB;

                using (var proc = Process.GetCurrentProcess()) {
                    privateMB   = proc.PrivateMemorySize64 / 1e+6;
                    peakPagedMB = proc.PeakPagedMemorySize64 / 1e+6;
                    workingMB   = proc.WorkingSet64 / 1e+6;
                }

                var te = new TelemetryEvent {
                    EventName = "python_language_server/analysis_complete", // TODO: Move this common prefix into Core.
                };

                te.Measurements["privateMB"]   = privateMB;
                te.Measurements["peakPagedMB"] = peakPagedMB;
                te.Measurements["workingMB"]   = workingMB;
                te.Measurements["elapsedMs"]   = e.MillisecondsElapsed;
                te.Measurements["moduleCount"] = e.ModuleCount;
                te.Measurements["rdtCount"]    = _rdt.DocumentCount;

                telemetry.SendTelemetryAsync(te).DoNotWait();
            } catch (Exception ex) when(!ex.IsCriticalException())
            {
                // Workaround for https://github.com/microsoft/python-language-server/issues/1820
                // On some systems random DLL may get missing or otherwise not installed
                // and we don't want to crash b/c of telemetry.
            }
        }
Ejemplo n.º 18
0
        void LogTelemetryEvent(string counterName)
        {
            const string numberOfPrefix = "numberof";

            if (counterName.StartsWith(numberOfPrefix, StringComparison.OrdinalIgnoreCase))
            {
                counterName = counterName.Substring(numberOfPrefix.Length);
            }

            var operation = new TelemetryEvent(Event.UsageTracker);

            operation.Properties[Property.TelemetryVersion] = TelemetryVersion;
            operation.Properties[Property.CounterName]      = counterName;
            operation.Properties[Property.ExtensionVersion] = AssemblyVersionInformation.Version;
            operation.Properties[Property.IsGitHubUser]     = IsGitHubUser;
            operation.Properties[Property.IsEnterpriseUser] = IsEnterpriseUser;

            TelemetryService.DefaultSession.PostEvent(operation);
        }
        /// <summary>
        /// Maps a <see cref="EventWrittenEventArgs"/> to a <see cref="TelemetryEvent"/>.
        /// </summary>
        /// <param name="source">An event to map.</param>
        /// <param name="sessionName">A session name to add to the destination object.</param>
        /// <returns>A instance of <see cref="TelemetryEvent"/>.</returns>
        public static TelemetryEvent Map(this EventWrittenEventArgs source, string sessionName)
        {
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }

            if (string.IsNullOrWhiteSpace(sessionName))
            {
                throw new ArgumentNullException(nameof(sessionName));
            }

            TelemetryEvent destination = new TelemetryEvent
            {
                ApplicationId     = source.GetApplicationId(),
                AttachmentId      = source.GetAttachmentId(),
                Channel           = (int)source.Channel,
                Id                = source.EventId,
                Level             = source.Level,
                Message           = source.GetFormattedMessage(),
                Name              = source.EventName,
                Payloads          = source.GetPayloads(),
                ProcessId         = 0,
                ProcessName       = null,
                ProviderId        = source.EventSource.Guid,
                ProviderName      = source.EventSource.Name,
                OpcodeId          = (int)source.Opcode,
                OpcodeName        = source.Opcode.ToString(),
                ActivityId        = source.GetActivityId(),
                RelatedActivityId = source.RelatedActivityId,
                Keywords          = source.Keywords,
                SessionName       = sessionName,
                TaskId            = (int)source.Task,
                TaskName          = source.Task.ToString(),
                ThreadId          = 0,
                Timestamp         = DateTime.UtcNow.Ticks,
                UserId            = source.GetUserId(),
                Version           = source.Version
            };

            return(destination);
        }
Ejemplo n.º 20
0
        static void Main(string[] args)
        {
            string appInsightsInstrumentationKey = GetAppInsightsInstrumentationKey();

            if (string.IsNullOrWhiteSpace(appInsightsInstrumentationKey))
            {
                throw new Exception("No App Insights Instrumentation Key could be retrieved from configuration!");
            }

            AppInsightsTelemetrySink sink = new AppInsightsTelemetrySink(appInsightsInstrumentationKey);

            List <TelemetryEvent> events = new List <TelemetryEvent>();

            for (int i = 1; i <= 10; i++)
            {
                TelemetryEvent te = new TelemetryEvent();
                te.Duration       = new TimeSpan(0, 3, 5);
                te.EventTypeValue = TelemetryEvent.EventTypes.Event;
                te.Id             = Guid.NewGuid().ToString();
                te.LevelValue     = TelemetryEvent.Levels.Information;
                te.Message        = "Message " + i.ToString();
                te.Metrics.Add("FooMetric", i);
                te.Value     = i;
                te.Name      = "Event " + i.ToString();
                te.ProblemId = "Problem " + i.ToString();
                te.Properties.Add("FooProperty", i.ToString());
                te.ResponseCode = "200";
                te.Result       = "Success";
                te.Success      = true;
                te.Target       = "FooTarget";
                te.TimeStamp    = DateTime.UtcNow;
                te.Uri          = "http://portal.azure.com";
                te.UserId       = "pelazem";
                te.Version      = "1.0";

                events.Add(te);
            }

            sink.Send(events);

            sink.Client.Flush();
        }
Ejemplo n.º 21
0
        public static void LogEventIfAllowed(ITelemetry telemetry, TelemetryEvent telemetryEvent)
        {
            if (!telemetry.Enabled)
            {
                return;
            }

            telemetryEvent.Parameters = telemetryEvent.Parameters ?? new List <string>();
            var properties = new Dictionary <string, string>
            {
                { "commandName", telemetryEvent.CommandName },
                { "iActionName", telemetryEvent.IActionName },
                { "parameters", string.Join(",", telemetryEvent.Parameters) },
                { "prefixOrScriptRoot", telemetryEvent.PrefixOrScriptRoot.ToString() },
                { "parseError", telemetryEvent.ParseError.ToString() },
                { "isSuccessful", telemetryEvent.IsSuccessful.ToString() }
            };

            if (telemetryEvent.CommandEvents != null)
            {
                foreach (KeyValuePair <string, string> keyValue in telemetryEvent.CommandEvents)
                {
                    properties[keyValue.Key] = keyValue.Value;
                }
            }

            if (telemetryEvent.GlobalSettings != null)
            {
                foreach (KeyValuePair <string, string> keyValue in telemetryEvent.GlobalSettings)
                {
                    properties[$"global_{keyValue.Key}"] = keyValue.Value;
                }
            }

            var measurements = new Dictionary <string, double>
            {
                { "timeTaken", telemetryEvent.TimeTaken }
            };

            telemetry.TrackEvent(telemetryEvent.CommandName, properties, measurements);
            telemetry.Flush();
        }
        public virtual void Track(IConfiguration config, TelemetryEvent tEvent)
        {
            EnsureInitialized();

            if (processors.ContainsKey(tEvent))
            {
                try
                {
                    processors[tEvent].ProcessEvent(config);
                }
                catch (Exception ex)
                {
                    Log.Error($"Exception occurred during sendning '{tEvent}' telemetry event. {ex.Message}, {ex.StackTrace}");
                }
            }
            else
            {
                Log.Debug($"There is no defined processor for '{tEvent}'");
            }
        }
Ejemplo n.º 23
0
        public void TelemetryTest_TelemetryActivityWithEmptyParentId()
        {
            // Arrange
            var            telemetryService = new Mock <INuGetTelemetryService>();
            TelemetryEvent telemetryEvent   = null;
            var            parentId         = Guid.Empty;

            telemetryService.Setup(x => x.EmitTelemetryEvent(It.IsAny <TelemetryEvent>()))
            .Callback <TelemetryEvent>(x => telemetryEvent = x);
            TelemetryActivity.NuGetTelemetryService        = telemetryService.Object;

            // Act
            using (var telemetry = new TelemetryActivity(parentId))
            {
                telemetry.TelemetryEvent = new TelemetryEvent("testEvent", new Dictionary <string, object>());
            }

            // Assert
            Assert.Null(telemetryEvent["ParentId"]);
        }
Ejemplo n.º 24
0
        public void LogEvent(PythonLogEvent logEvent, object argument)
        {
            // No session is not a fatal error.
            // Never send events when users have not opted in.
            if (_session.Value == null || !_session.Value.IsOptedIn)
            {
                return;
            }

            // Certain events are not collected
            switch (logEvent)
            {
            case PythonLogEvent.PythonPackage:
                lock (_seenPackages) {
                    var name = (argument as PackageInfo)?.Name;
                    // Don't send empty or repeated names
                    if (string.IsNullOrEmpty(name) || !_seenPackages.Add(name))
                    {
                        return;
                    }
                }
                break;
            }

            var evt   = new TelemetryEvent(EventPrefix + logEvent.ToString());
            var props = PythonToolsLoggerData.AsDictionary(argument);

            if (props != null)
            {
                foreach (var kv in props)
                {
                    evt.Properties[PropertyPrefix + kv.Key] = kv.Value;
                }
            }
            else if (argument != null)
            {
                evt.Properties[PropertyPrefix + "Value"] = argument;
            }

            _session.Value.PostEvent(evt);
        }
Ejemplo n.º 25
0
        public void LogEvent(string eventName, IReadOnlyDictionary <string, object> properties, IReadOnlyDictionary <string, double> measurements)
        {
            // No session is not a fatal error.
            // Never send events when users have not opted in.
            if (_session.Value == null || !_session.Value.IsOptedIn)
            {
                return;
            }

            var evt = new TelemetryEvent($"{EventPrefix}{eventName}");

            foreach (var p in properties.MaybeEnumerate())
            {
                evt.Properties[p.Key] = p.Value;
            }
            foreach (var p in measurements.MaybeEnumerate())
            {
                evt.Properties[p.Key] = new TelemetryMetricProperty(p.Value);
            }
            _session.Value.PostEvent(evt);
        }
        public static TelemetryEvent GetUpgradeTelemetryEvent(
            IEnumerable <NuGetProject> projects,
            NuGetOperationStatus status,
            int packageCount)
        {
            var eventName = "UpgradeInformation";

            var sortedProjects = projects.OrderBy(
                project => project.GetMetadata <string>(NuGetProjectMetadataKeys.UniqueName));

            var projectIds = sortedProjects.Select(
                project => project.GetMetadata <string>(NuGetProjectMetadataKeys.ProjectId)).ToArray();

            var telemetryEvent = new TelemetryEvent(eventName);

            telemetryEvent["ProjectIds"]   = string.Join(",", projectIds);
            telemetryEvent["Status"]       = status;
            telemetryEvent["PackageCount"] = packageCount;

            return(telemetryEvent);
        }
Ejemplo n.º 27
0
        public void EmitCpsBulkFileRestoreCoordinationEvent_Succeeds()
        {
            // Arrange
            var            telemetrySession   = new Mock <ITelemetrySession>();
            TelemetryEvent lastTelemetryEvent = null;

            _ = telemetrySession
                .Setup(x => x.PostEvent(It.IsAny <TelemetryEvent>()))
                .Callback <TelemetryEvent>(x => lastTelemetryEvent = x);

            var service = new NuGetVSTelemetryService(telemetrySession.Object);

            var evt = new CpsBulkFileRestoreCoordinationEvent();

            // Act
            service.EmitTelemetryEvent(evt);

            // Assert
            Assert.NotNull(lastTelemetryEvent);
            Assert.Equal(evt.Name, lastTelemetryEvent.Name);
        }
Ejemplo n.º 28
0
 private void ProcessPostedEvents(TelemetryEvent telemetryEvent)
 {
     KeyValuePair <int, Subscription>[] array;
     lock (lockObject)
     {
         array = Subscriptions.ToArray();
     }
     KeyValuePair <int, Subscription>[] array2 = array;
     for (int i = 0; i < array2.Length; i++)
     {
         KeyValuePair <int, Subscription> keyValuePair = array2[i];
         Subscription value = keyValuePair.Value;
         bool         flag  = false;
         try
         {
             flag = value.Match.IsEventMatch(telemetryEvent);
         }
         catch (Exception exception)
         {
             PostFaultEvent("VS/Core/TelemetryNotification/FilterFault", value.Match, exception);
             Unsubscribe(keyValuePair.Key);
         }
         if (flag)
         {
             if (value.SingleNotification)
             {
                 Unsubscribe(keyValuePair.Key);
             }
             try
             {
                 TelemetryEvent obj = telemetryEvent.CloneTelemetryEvent();
                 value.Handler(obj);
             }
             catch (Exception exception2)
             {
                 PostFaultEvent("VS/Core/TelemetryNotification/HandlerFault", value.Match, exception2);
             }
         }
     }
 }
        public void Start()
        {
            RequestActivityEventSource.Log.Listen(listener =>
            {
                // arrange
                const string expectedMessage = "Request GET http://127.0.0.1/api/events";
                Guid activityId = Guid.NewGuid();

                // act
                RequestActivityEventSource.Log.Start(activityId, "GET", "http://127.0.0.1/api/events");

                // assert
                TelemetryEvent firstItem = listener
                                           .OrderedEvents
                                           .Select(e => e.Map("2338"))
                                           .FirstOrDefault(e => e.Message == expectedMessage);

                Assert.NotNull(firstItem);
                Assert.Equal(EventLevel.LogAlways, firstItem.Level);
                AssertItem(firstItem, 2, activityId, expectedMessage);
            });
        }
        public void BeginTransfer()
        {
            RequestActivityEventSource.Log.Listen((listener) =>
            {
                // arrange
                const string expectedMessage = "Begin activity transfer";
                Guid activityId = Guid.NewGuid();

                // act
                RequestActivityEventSource.Log.BeginTransfer(activityId);

                // assert
                TelemetryEvent firstItem = listener
                                           .OrderedEvents
                                           .Select(e => e.Map("8768"))
                                           .FirstOrDefault(e => e.Message == expectedMessage);

                Assert.NotNull(firstItem);
                Assert.Equal(EventLevel.LogAlways, firstItem.Level);
                AssertItem(firstItem, 0, activityId, expectedMessage);
            });
        }
        public void OuterActivityNotAllowed()
        {
            RequestActivityEventSource.Log.Listen((listener) =>
            {
                // arrange
                const string expectedMessage = "Outer activities are not allowed when creating a server-side message activity.";
                Guid activityId = Guid.NewGuid();

                // act
                RequestActivityEventSource.Log.OuterActivityNotAllowed(activityId);

                // assert
                TelemetryEvent firstItem = listener
                                           .OrderedEvents
                                           .Select(e => e.Map("7778"))
                                           .FirstOrDefault(e => e.Message == expectedMessage);

                Assert.NotNull(firstItem);
                Assert.Equal(EventLevel.Warning, firstItem.Level);
                AssertItem(firstItem, 0, activityId, expectedMessage);
            });
        }
Ejemplo n.º 32
0
        public void TelemetryTest_TelemetryActivityWithIntervalMeasure()
        {
            // Arrange
            var            telemetryService = new Mock <INuGetTelemetryService>();
            TelemetryEvent telemetryEvent   = null;

            telemetryService.Setup(x => x.EmitTelemetryEvent(It.IsAny <TelemetryEvent>()))
            .Callback <TelemetryEvent>(x => telemetryEvent = x);
            TelemetryActivity.NuGetTelemetryService        = telemetryService.Object;

            // Act
            using (var telemetry = TelemetryActivity.CreateTelemetryActivityWithNewOperationId())
            {
                telemetry.TelemetryEvent = new TelemetryEvent("testEvent", new Dictionary <string, object>());
                telemetry.StartIntervalMeasure();
                Thread.Sleep(5000);
                telemetry.EndIntervalMeasure("testInterval");
            }

            // Assert
            Assert.Equal(5, Convert.ToInt32(telemetryEvent["testInterval"]));
        }
Ejemplo n.º 33
0
        public void TelemetryTest_TelemetryActivityWithOperationId()
        {
            // Arrange
            var            telemetryService = new Mock <INuGetTelemetryService>();
            TelemetryEvent telemetryEvent   = null;
            Guid           operationId;

            telemetryService.Setup(x => x.EmitTelemetryEvent(It.IsAny <TelemetryEvent>()))
            .Callback <TelemetryEvent>(x => telemetryEvent = x);
            TelemetryActivity.NuGetTelemetryService        = telemetryService.Object;

            // Act
            using (var telemetry = TelemetryActivity.CreateTelemetryActivityWithNewOperationId())
            {
                telemetry.TelemetryEvent = new TelemetryEvent("testEvent", new Dictionary <string, object>());
                operationId = telemetry.OperationId;
            }

            // Assert
            Assert.Null(telemetryEvent["ParentId"]);
            Assert.Equal(operationId.ToString(), telemetryEvent["OperationId"]);
        }
 void ITelemetryLogger.ReportEvent(TelemetryEvent telemetryEvent)
 {
     this.events.Add(telemetryEvent);
 }
 public void AssertSingleEventWasWritten(TelemetryEvent expected)
 {
     Assert.AreEqual(1, this.events.Count, "Unexpected events: {0}", string.Join(", ", this.events));
     TelemetryEvent actual = this.events.Single();
     Assert.AreEqual(expected, actual, "Unexpected entry name");
 }
Ejemplo n.º 36
0
 /// <summary>
 /// Records telemetry event
 /// </summary>
 /// <param name="telemetryEvent"></param>
 public void RecordEvent(TelemetryEvent telemetryEvent) {
     if (this.IsEnabled) {
         _session.PostEvent(telemetryEvent);
     }
 }