コード例 #1
0
        public async Task LogException_SinksToApplicationInsightsWithIncludedProperties_ResultsInExceptionTelemetry()
        {
            // Arrange
            string message          = BogusGenerator.Lorem.Sentence();
            string expectedProperty = BogusGenerator.Lorem.Word();
            var    exception        = new TestException(message)
            {
                SpyProperty = expectedProperty
            };

            using (ILoggerFactory loggerFactory = CreateLoggerFactory(configureOptions: options => options.Exception.IncludeProperties = true))
            {
                ILogger logger = loggerFactory.CreateLogger <ApplicationInsightsSinkTests>();

                // Act
                logger.LogCritical(exception, exception.Message);
            }

            // Assert
            using (ApplicationInsightsDataClient client = CreateApplicationInsightsClient())
            {
                await RetryAssertUntilTelemetryShouldBeAvailableAsync(async() =>
                {
                    EventsResults <EventsExceptionResult> results = await client.Events.GetExceptionEventsAsync(ApplicationId, filter: OnlyLastHourFilter);
                    Assert.Contains(results.Value, result =>
                    {
                        return(result.Exception.OuterMessage == exception.Message &&
                               result.CustomDimensions.TryGetValue($"Exception-{nameof(TestException.SpyProperty)}", out string actualProperty) &&
                               expectedProperty == actualProperty);
                    });
                });
            }
        }
コード例 #2
0
        public async Task LogExceptionWithComponentName_SinksToApplicationInsights_ResultsInTelemetryWithComponentName()
        {
            // Arrange
            string message       = BogusGenerator.Lorem.Sentence();
            string componentName = BogusGenerator.Commerce.ProductName();
            var    exception     = new PlatformNotSupportedException(message);

            using (ILoggerFactory loggerFactory = CreateLoggerFactory(config => config.Enrich.WithComponentName(componentName)))
            {
                ILogger logger = loggerFactory.CreateLogger <ApplicationInsightsSinkTests>();

                // Act
                logger.LogCritical(exception, exception.Message);
            }

            // Assert
            using (ApplicationInsightsDataClient client = CreateApplicationInsightsClient())
            {
                await RetryAssertUntilTelemetryShouldBeAvailableAsync(async() =>
                {
                    EventsResults <EventsExceptionResult> results = await client.Events.GetExceptionEventsAsync(ApplicationId, filter: OnlyLastHourFilter);
                    Assert.NotEmpty(results.Value);
                    Assert.Contains(results.Value, result => result.Exception.OuterMessage == exception.Message && result.Cloud.RoleName == componentName);
                });
            }
        }
コード例 #3
0
        public async Task LogIoTHubDependency_SinksToApplicationInsights_ResultsIEventHubsDependencyTelemetry()
        {
            // Arrange
            string componentName = BogusGenerator.Commerce.ProductName();
            string iotHubName    = BogusGenerator.Commerce.ProductName();

            using (ILoggerFactory loggerFactory = CreateLoggerFactory(config => config.Enrich.WithComponentName(componentName)))
            {
                ILogger logger = loggerFactory.CreateLogger <ApplicationInsightsSinkTests>();

                bool           isSuccessful = BogusGenerator.PickRandom(true, false);
                DateTimeOffset startTime    = BogusGenerator.Date.RecentOffset(days: 0);
                TimeSpan       duration     = BogusGenerator.Date.Timespan();
                Dictionary <string, object> telemetryContext = CreateTestTelemetryContext();

                // Act
                logger.LogIotHubDependency(iotHubName, isSuccessful, startTime, duration, telemetryContext);
            }

            // Assert
            using (ApplicationInsightsDataClient client = CreateApplicationInsightsClient())
            {
                await RetryAssertUntilTelemetryShouldBeAvailableAsync(async() =>
                {
                    EventsResults <EventsDependencyResult> results = await client.Events.GetDependencyEventsAsync(ApplicationId);
                    Assert.NotEmpty(results.Value);
                    Assert.Contains(results.Value, result =>
                    {
                        return(result.Dependency.Type == "Azure IoT Hub" &&
                               result.Dependency.Target == iotHubName &&
                               result.Cloud.RoleName == componentName);
                    });
                });
            }
        }
コード例 #4
0
        public async Task LogDependency_SinksToApplicationInsights_ResultsInDependencyTelemetry()
        {
            // Arrange
            string dependencyType = "Arcus";
            string dependencyData = BogusGenerator.Finance.Account();

            using (ILoggerFactory loggerFactory = CreateLoggerFactory())
            {
                ILogger logger = loggerFactory.CreateLogger <ApplicationInsightsSinkTests>();

                bool           isSuccessful = BogusGenerator.PickRandom(true, false);
                DateTimeOffset startTime    = DateTimeOffset.Now;
                TimeSpan       duration     = BogusGenerator.Date.Timespan();
                Dictionary <string, object> telemetryContext = CreateTestTelemetryContext();

                // Act
                logger.LogDependency(dependencyType, dependencyData, isSuccessful, startTime, duration, telemetryContext);
            }

            // Assert
            using (ApplicationInsightsDataClient client = CreateApplicationInsightsClient())
            {
                await RetryAssertUntilTelemetryShouldBeAvailableAsync(async() =>
                {
                    EventsResults <EventsDependencyResult> results = await client.Events.GetDependencyEventsAsync(ApplicationId, timespan: "PT30M");
                    Assert.NotEmpty(results.Value);
                    Assert.Contains(results.Value, result => result.Dependency.Type == dependencyType && result.Dependency.Data == dependencyData);
                });
            }
        }
コード例 #5
0
        public async Task LogServiceBusDependency_SinksToApplicationInsights_ResultsInServiceBusDependencyTelemetry()
        {
            // Arrange
            string entityName = BogusGenerator.Commerce.Product();

            using (ILoggerFactory loggerFactory = CreateLoggerFactory())
            {
                ILogger logger = loggerFactory.CreateLogger <ApplicationInsightsSinkTests>();

                bool           isSuccessful = BogusGenerator.PickRandom(true, false);
                DateTimeOffset startTime    = DateTimeOffset.Now;
                TimeSpan       duration     = BogusGenerator.Date.Timespan();
                Dictionary <string, object> telemetryContext = CreateTestTelemetryContext();

                // Act
                logger.LogServiceBusDependency(entityName, isSuccessful, startTime, duration, ServiceBusEntityType.Queue, telemetryContext);
            }

            // Assert
            using (ApplicationInsightsDataClient client = CreateApplicationInsightsClient())
            {
                await RetryAssertUntilTelemetryShouldBeAvailableAsync(async() =>
                {
                    EventsResults <EventsDependencyResult> results = await client.Events.GetDependencyEventsAsync(ApplicationId, timespan: "PT30M");
                    Assert.NotEmpty(results.Value);
                    Assert.Contains(results.Value, result => result.Dependency.Type == "Azure Service Bus" && result.Dependency.Target == entityName);
                });
            }
        }
コード例 #6
0
        public async Task LogEventWithVersion_SinksToApplicationInsights_ResultsInTelemetryWithVersion()
        {
            // Arrange
            var eventName = "Update version";

            using (ILoggerFactory loggerFactory = CreateLoggerFactory(config => config.Enrich.WithVersion()))
            {
                ILogger logger = loggerFactory.CreateLogger <ApplicationInsightsSinkTests>();

                // Act
                logger.LogEvent(eventName);
            }

            // Assert
            using (ApplicationInsightsDataClient client = CreateApplicationInsightsClient())
            {
                await RetryAssertUntilTelemetryShouldBeAvailableAsync(async() =>
                {
                    EventsResults <EventsCustomEventResult> events = await client.Events.GetCustomEventsAsync(ApplicationId, filter: OnlyLastHourFilter);
                    Assert.Contains(events.Value, ev =>
                    {
                        return(ev.CustomEvent.Name == eventName &&
                               ev.CustomDimensions.TryGetValue(VersionEnricher.DefaultPropertyName, out string actualVersion) &&
                               !String.IsNullOrWhiteSpace(actualVersion));
                    });
                });
            }
        }
コード例 #7
0
        public async Task LogEventWithCorrelationInfo_SinksToApplicationInsights_ResultsInTelemetryWithCorrelationInfo()
        {
            // Arrange
            string message       = "Message that will be correlated";
            string operationId   = $"operation-{Guid.NewGuid()}";
            string transactionId = $"transaction-{Guid.NewGuid()}";

            DefaultCorrelationInfoAccessor.Instance.SetCorrelationInfo(new CorrelationInfo(operationId, transactionId));
            using (ILoggerFactory loggerFactory = CreateLoggerFactory(config => config.Enrich.WithCorrelationInfo()))
            {
                ILogger logger = loggerFactory.CreateLogger <ApplicationInsightsSinkTests>();

                // Act
                logger.LogInformation(message);
            }

            // Assert
            using (ApplicationInsightsDataClient client = CreateApplicationInsightsClient())
            {
                await RetryAssertUntilTelemetryShouldBeAvailableAsync(async() =>
                {
                    EventsResults <EventsTraceResult> traceEvents = await client.Events.GetTraceEventsAsync(ApplicationId, filter: OnlyLastHourFilter);
                    Assert.Contains(traceEvents.Value, trace =>
                    {
                        return(message == trace.Trace.Message &&
                               trace.CustomDimensions.TryGetValue(ContextProperties.Correlation.OperationId, out string actualOperationId) &&
                               operationId == actualOperationId &&
                               trace.CustomDimensions.TryGetValue(ContextProperties.Correlation.TransactionId, out string actualTransactionId) &&
                               transactionId == actualTransactionId);
                    });
                });
            }
        }
コード例 #8
0
        public async Task GetSabotagedEndpoint_TracksFailedResponse_ReturnsFailedResponse()
        {
            // Arrange
            var optionsWithSerilogLogging =
                new WebApiProjectOptions().WithSerilogLogging(ApplicationInsightsConfig.InstrumentationKey);

            using (var project = WebApiProject.CreateNew(Configuration, optionsWithSerilogLogging, Logger))
            {
                project.AddTypeAsFile <SaboteurController>();
                await project.StartAsync();

                // Act
                using (HttpResponseMessage response = await project.Root.GetAsync(SaboteurController.Route))
                {
                    // Assert
                    Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
                    await RetryAssertUntilTelemetryShouldBeAvailableAsync(async client =>
                    {
                        EventsResults <EventsRequestResult> results =
                            await client.Events.GetRequestEventsAsync(ApplicationInsightsConfig.ApplicationId, filter: OnlyLastHourFilter);

                        Assert.Contains(results.Value, result =>
                        {
                            return(result.Request.Url.Contains("sabotage") && result.Request.ResultCode == "500");
                        });
                    });
                }
            }
        }
コード例 #9
0
        public async Task LogRequestMessage_SinksToApplicationInsightsWithResponse_ResultsInRequestTelemetry()
        {
            // Arrange
            var requestUri = new Uri(BogusGenerator.Internet.Url());

            using (ILoggerFactory loggerFactory = CreateLoggerFactory())
            {
                ILogger logger = loggerFactory.CreateLogger <ApplicationInsightsSinkTests>();

                HttpMethod httpMethod = GenerateHttpMethod();
                var        request    = new HttpRequestMessage(httpMethod, requestUri);

                var statusCode = BogusGenerator.PickRandom <HttpStatusCode>();
                var response   = new HttpResponseMessage(statusCode);

                var duration = BogusGenerator.Date.Timespan();
                Dictionary <string, object> telemetryContext = CreateTestTelemetryContext();

                // Act
                logger.LogRequest(request, response, duration, telemetryContext);
            }

            // Assert
            using (ApplicationInsightsDataClient client = CreateApplicationInsightsClient())
            {
                await RetryAssertUntilTelemetryShouldBeAvailableAsync(async() =>
                {
                    EventsResults <EventsRequestResult> results = await client.Events.GetRequestEventsAsync(ApplicationId, filter: OnlyLastHourFilter);
                    Assert.NotEmpty(results.Value);
                    Assert.Contains(results.Value, result => result.Request.Url == requestUri.ToString());
                });
            }
        }
コード例 #10
0
 public ServiceResult <EventsResults> GetEvents(int length)
 {
     try
     {
         this.GetClient();
         string address = $"/v3/users/{this._eb_user}/events/?token={this._token}";
         //string str2 = this.client.DownloadString(address);
         client.BaseAddress = new Uri(this._baseURL);
         HttpResponseMessage response         = client.GetAsync(address).Result;
         var responseString                   = response.Content.ReadAsStringAsync().Result;
         ServiceResult <EventsResults> result = new ServiceResult <EventsResults>(true, JsonConvert.DeserializeObject <EventsResults>(responseString), "");
         EventsResults results                = new EventsResults();
         if (result.Data.Pagination.page_count > 1)
         {
             for (int i = 0; i < result.Data.Pagination.page_count; i++)
             {
                 string address1 = $"/v3/users/{this._eb_user}/events/?token={this._token}&page={i + 1}";
                 //string str4 = this.client.DownloadString(str3);
                 //client.BaseAddress = new Uri(this._baseURL);
                 HttpResponseMessage response1         = client.GetAsync(address1).Result;
                 var responseString1                   = response1.Content.ReadAsStringAsync().Result;
                 ServiceResult <EventsResults> result2 = new ServiceResult <EventsResults>(true, JsonConvert.DeserializeObject <EventsResults>(responseString1), "");
                 if (results.events == null)
                 {
                     results.events = new List <Event>();
                 }
                 if (result2.Data.events != null)
                 {
                     results.events.AddRange(result2.Data.events);
                 }
             }
         }
         else
         {
             results.events = result.Data.events;
         }
         foreach (Event event2 in results.events)
         {
             event2.description.text = this.Truncate(event2.description.text, length);
         }
         return(new ServiceResult <EventsResults>(true, results, ""));
     }
     catch (Exception exception)
     {
         this.GetClient();
         return(new ServiceResult <EventsResults>(false, new EventsResults(), exception.Message));
     }
 }
コード例 #11
0
        public async Task LogHttpDependencyWithComponentName_SinksToApplicationInsights_ResultsInHttpDependencyTelemetryWithComponentName()
        {
            // Arrange
            string     componentName = BogusGenerator.Commerce.ProductName();
            HttpMethod httpMethod    = GenerateHttpMethod();
            string     requestUrl    = BogusGenerator.Image.LoremFlickrUrl();

            using (ILoggerFactory loggerFactory = CreateLoggerFactory(config => config.Enrich.WithComponentName(componentName)))
            {
                ILogger logger = loggerFactory.CreateLogger <ApplicationInsightsSinkTests>();

                var request = new HttpRequestMessage(httpMethod, requestUrl)
                {
                    Content = new StringContent(BogusGenerator.Lorem.Paragraph())
                };
                var statusCode = BogusGenerator.PickRandom <HttpStatusCode>();
                var duration   = BogusGenerator.Date.Timespan();
                Dictionary <string, object> telemetryContext = CreateTestTelemetryContext();

                // Act
                logger.LogHttpDependency(request, statusCode, DateTimeOffset.UtcNow, duration, telemetryContext);
            }

            // Assert
            var requestUri = new Uri(requestUrl);

            using (ApplicationInsightsDataClient client = CreateApplicationInsightsClient())
            {
                await RetryAssertUntilTelemetryShouldBeAvailableAsync(async() =>
                {
                    EventsResults <EventsDependencyResult> results = await client.Events.GetDependencyEventsAsync(ApplicationId);
                    Assert.NotEmpty(results.Value);
                    Assert.Contains(results.Value, result =>
                    {
                        return(result.Dependency.Type == "HTTP" &&
                               result.Dependency.Target == requestUri.Host &&
                               result.Dependency.Name == $"{httpMethod} {requestUri.AbsolutePath}" &&
                               result.Cloud.RoleName == componentName);
                    });
                });
            }
        }
コード例 #12
0
        public async Task LogEventWithCorrelationInfo_SinksToApplicationInsights_ResultsInTelemetryWithCorrelationInfo()
        {
            // Arrange
            string message           = "Message that will be correlated";
            string operationId       = $"operation-{Guid.NewGuid()}";
            string transactionId     = $"transaction-{Guid.NewGuid()}";
            string operationParentId = $"operation-parent-{Guid.NewGuid()}";

            var correlationInfoAccessor = new DefaultCorrelationInfoAccessor();

            correlationInfoAccessor.SetCorrelationInfo(new CorrelationInfo(operationId, transactionId, operationParentId));

            using (ILoggerFactory loggerFactory = CreateLoggerFactory(config => config.Enrich.WithCorrelationInfo(correlationInfoAccessor)))
            {
                ILogger logger = loggerFactory.CreateLogger <ApplicationInsightsSinkTests>();

                // Act
                logger.LogInformation(message);
            }

            // Assert
            using (ApplicationInsightsDataClient client = CreateApplicationInsightsClient())
            {
                await RetryAssertUntilTelemetryShouldBeAvailableAsync(async() =>
                {
                    EventsResults <EventsTraceResult> traceEvents = await client.Events.GetTraceEventsAsync(ApplicationId, filter: OnlyLastHourFilter);

                    AssertX.Any(traceEvents.Value, trace =>
                    {
                        Assert.Equal(message, trace.Trace.Message);
                        Assert.True(trace.CustomDimensions.TryGetValue(ContextProperties.Correlation.OperationId, out string actualOperationId), "Requires a operation ID in the custom dimensions");
                        Assert.True(trace.CustomDimensions.TryGetValue(ContextProperties.Correlation.TransactionId, out string actualTransactionId), "Requires a transaction ID in the custom dimensions");
                        Assert.True(trace.CustomDimensions.TryGetValue(ContextProperties.Correlation.OperationParentId, out string actualOperationParentId), "Requires a operation parent ID in the custom dimensions");

                        Assert.Equal(operationId, actualOperationId);
                        Assert.Equal(transactionId, actualTransactionId);
                        Assert.Equal(operationParentId, actualOperationParentId);
                        Assert.Equal(operationId, trace.Operation.Id);
                        Assert.Equal(operationParentId, trace.Operation.ParentId);
                    });
                });
コード例 #13
0
        public async Task LogExceptionWithCorrelationInfo_SinksToApplicationInsights_ResultsInTelemetryWithCorrelationInfo()
        {
            // Arrange
            string message   = BogusGenerator.Lorem.Sentence();
            var    exception = new PlatformNotSupportedException(message);

            string operationId       = $"operation-{Guid.NewGuid()}";
            string transactionId     = $"transaction-{Guid.NewGuid()}";
            string operationParentId = $"operation-parent-{Guid.NewGuid()}";

            var correlationInfoAccessor = new DefaultCorrelationInfoAccessor();

            correlationInfoAccessor.SetCorrelationInfo(new CorrelationInfo(operationId, transactionId, operationParentId));

            using (ILoggerFactory loggerFactory = CreateLoggerFactory(config => config.Enrich.WithCorrelationInfo(correlationInfoAccessor)))
            {
                ILogger logger = loggerFactory.CreateLogger <ApplicationInsightsSinkTests>();

                // Act
                logger.LogCritical(exception, exception.Message);
            }

            // Assert
            using (ApplicationInsightsDataClient client = CreateApplicationInsightsClient())
            {
                await RetryAssertUntilTelemetryShouldBeAvailableAsync(async() =>
                {
                    EventsResults <EventsExceptionResult> results = await client.Events.GetExceptionEventsAsync(ApplicationId, filter: OnlyLastHourFilter);
                    Assert.NotEmpty(results.Value);

                    AssertX.Any(results.Value, result =>
                    {
                        Assert.Equal(exception.Message, result.Exception.OuterMessage);
                        Assert.Equal(operationId, result.Operation.Id);
                        Assert.Equal(operationParentId, result.Operation.ParentId);
                    });
                });
            }
        }
コード例 #14
0
        public async Task LogSqlDependency_SinksToApplicationInsights_ResultsInSqlDependencyTelemetry()
        {
            // Arrange
            string serverName   = BogusGenerator.Database.Engine();
            string databaseName = BogusGenerator.Database.Collation();
            string tableName    = BogusGenerator.Database.Column();

            using (ILoggerFactory loggerFactory = CreateLoggerFactory())
            {
                ILogger logger = loggerFactory.CreateLogger <ApplicationInsightsSinkTests>();

                string         operation    = BogusGenerator.PickRandom("GET", "UPDATE", "DELETE", "CREATE");
                bool           isSuccessful = BogusGenerator.PickRandom(true, false);
                DateTimeOffset startTime    = DateTimeOffset.Now;
                TimeSpan       duration     = BogusGenerator.Date.Timespan();
                Dictionary <string, object> telemetryContext = CreateTestTelemetryContext();

                // Act
                logger.LogSqlDependency(serverName, databaseName, tableName, operation, isSuccessful, startTime, duration, telemetryContext);
            }

            // Assert
            using (ApplicationInsightsDataClient client = CreateApplicationInsightsClient())
            {
                await RetryAssertUntilTelemetryShouldBeAvailableAsync(async() =>
                {
                    EventsResults <EventsDependencyResult> results =
                        await client.Events.GetDependencyEventsAsync(ApplicationId, timespan: "PT30M");
                    Assert.NotEmpty(results.Value);
                    Assert.Contains(results.Value, result =>
                    {
                        return(result.Dependency.Type == "SQL" &&
                               result.Dependency.Target == serverName &&
                               result.Dependency.Name == $"SQL: {databaseName}/{tableName}");
                    });
                });
            }
        }
コード例 #15
0
        public async Task LogEventWithKubernetesInfo_SinksToApplicationInsights_ResultsInTelemetryWithKubernetesInfo()
        {
            // Arrange
            string nodeName   = $"node-{Guid.NewGuid()}";
            string podName    = $"pod-{Guid.NewGuid()}";
            string @namespace = $"namespace-{Guid.NewGuid()}";
            var    message    = "This message will have Kubernetes information";

            using (TemporaryEnvironmentVariable.Create(KubernetesEnricher.NodeNameVariable, nodeName))
                using (TemporaryEnvironmentVariable.Create(KubernetesEnricher.PodNameVariable, podName))
                    using (TemporaryEnvironmentVariable.Create(KubernetesEnricher.NamespaceVariable, @namespace))
                        using (ILoggerFactory loggerFactory = CreateLoggerFactory(config => config.Enrich.WithKubernetesInfo()))
                        {
                            ILogger logger = loggerFactory.CreateLogger <ApplicationInsightsSinkTests>();

                            // Act
                            logger.LogInformation(message);
                        }

            // Assert
            using (ApplicationInsightsDataClient client = CreateApplicationInsightsClient())
            {
                await RetryAssertUntilTelemetryShouldBeAvailableAsync(async() =>
                {
                    EventsResults <EventsTraceResult> traceEvents = await client.Events.GetTraceEventsAsync(ApplicationId, filter: OnlyLastHourFilter);
                    Assert.Contains(traceEvents.Value, trace =>
                    {
                        return(message == trace.Trace.Message &&
                               trace.CustomDimensions.TryGetValue(ContextProperties.Kubernetes.NodeName, out string actualNodeName) &&
                               nodeName == actualNodeName &&
                               trace.CustomDimensions.TryGetValue(ContextProperties.Kubernetes.PodName, out string actualPodName) &&
                               podName == actualPodName &&
                               trace.CustomDimensions.TryGetValue(ContextProperties.Kubernetes.Namespace, out string actualNamespace) &&
                               @namespace == actualNamespace);
                    });
                });
            }
        }
コード例 #16
0
        public async Task LogTableStorageDependency_SinksToApplicationInsights_ResultsInTableStorageDependencyTelemetry()
        {
            // Arrange
            string componentName = BogusGenerator.Commerce.ProductName();
            string tableName     = BogusGenerator.Commerce.ProductName();
            string accountName   = BogusGenerator.Finance.AccountName();

            using (ILoggerFactory loggerFactory = CreateLoggerFactory(config => LoggerEnrichmentConfigurationExtensions.WithComponentName(config.Enrich, componentName)))
            {
                ILogger logger = loggerFactory.CreateLogger <ApplicationInsightsSinkTests>();

                bool           isSuccessful = BogusGenerator.PickRandom(true, false);
                DateTimeOffset startTime    = DateTimeOffset.Now;
                TimeSpan       duration     = BogusGenerator.Date.Timespan();
                Dictionary <string, object> telemetryContext = CreateTestTelemetryContext();

                // Act
                logger.LogTableStorageDependency(accountName, tableName, isSuccessful, startTime, duration, telemetryContext);
            }

            // Assert
            using (ApplicationInsightsDataClient client = CreateApplicationInsightsClient())
            {
                await RetryAssertUntilTelemetryShouldBeAvailableAsync(async() =>
                {
                    EventsResults <EventsDependencyResult> results =
                        await client.Events.GetDependencyEventsAsync(ApplicationId, "PT30M");
                    Assert.NotEmpty(results.Value);
                    Assert.Contains(results.Value, result =>
                    {
                        return(result.Dependency.Type == "Azure table" &&
                               result.Dependency.Target == accountName &&
                               result.Dependency.Data == tableName &&
                               result.Cloud.RoleName == componentName);
                    });
                });
            }
        }
コード例 #17
0
        public async Task LogEvent_SinksToApplicationInsights_ResultsInEventTelemetry()
        {
            // Arrange
            string eventName = BogusGenerator.Finance.AccountName();

            using (ILoggerFactory loggerFactory = CreateLoggerFactory())
            {
                ILogger logger = loggerFactory.CreateLogger <ApplicationInsightsSinkTests>();
                Dictionary <string, object> telemetryContext = CreateTestTelemetryContext();

                // Act
                logger.LogEvent(eventName, telemetryContext);
            }

            // Assert
            using (ApplicationInsightsDataClient client = CreateApplicationInsightsClient())
            {
                await RetryAssertUntilTelemetryShouldBeAvailableAsync(async() =>
                {
                    EventsResults <EventsCustomEventResult> results = await client.Events.GetCustomEventsAsync(ApplicationId, filter: OnlyLastHourFilter);
                    Assert.Contains(results.Value, result => result.CustomEvent.Name == eventName);
                });
            }
        }
コード例 #18
0
        public async Task LogTrace_SinksToApplicationInsights_ResultsInTraceTelemetry()
        {
            // Arrange
            string message = BogusGenerator.Lorem.Sentence();

            using (ILoggerFactory loggerFactory = CreateLoggerFactory())
            {
                ILogger logger = loggerFactory.CreateLogger <ApplicationInsightsSinkTests>();
                Dictionary <string, object> telemetryContext = CreateTestTelemetryContext();

                // Act
                logger.LogInformation("Trace message '{Sentence}' (Context: {Context})", message, telemetryContext);
            }

            // Assert
            using (ApplicationInsightsDataClient client = CreateApplicationInsightsClient())
            {
                await RetryAssertUntilTelemetryShouldBeAvailableAsync(async() =>
                {
                    EventsResults <EventsTraceResult> results = await client.Events.GetTraceEventsAsync(ApplicationId, filter: OnlyLastHourFilter);
                    Assert.Contains(results.Value, result => result.Trace.Message.Contains(message));
                });
            }
        }
コード例 #19
0
        public async Task LogAzureKeyVaultDependency_SinksToApplicationInsights_ResultsInAzureKeyVaultDependencyTelemetry()
        {
            // Arrange
            string vaultUri   = "https://myvault.vault.azure.net";
            string secretName = "MySecret";

            using (ILoggerFactory loggerFactory = CreateLoggerFactory())
            {
                ILogger logger = loggerFactory.CreateLogger <AzureKeyVaultDependencyTests>();

                bool           isSuccessful = BogusGenerator.PickRandom(true, false);
                DateTimeOffset startTime    = DateTimeOffset.Now;
                TimeSpan       duration     = BogusGenerator.Date.Timespan();
                Dictionary <string, object> telemetryContext = CreateTestTelemetryContext();

                // Act
                logger.LogAzureKeyVaultDependency(vaultUri, secretName, isSuccessful, startTime, duration, telemetryContext);
            }

            // Assert
            using (IApplicationInsightsDataClient client = CreateApplicationInsightsClient())
            {
                await RetryAssertUntilTelemetryShouldBeAvailableAsync(async() =>
                {
                    EventsResults <EventsDependencyResult> results =
                        await client.Events.GetDependencyEventsAsync(ApplicationId, timespan: "PT30M");
                    Assert.NotEmpty(results.Value);
                    Assert.Contains(results.Value, result =>
                    {
                        return(result.Dependency.Type == "Azure key vault" &&
                               result.Dependency.Target == vaultUri &&
                               result.Dependency.Data == secretName);
                    });
                });
            }
        }