/// <summary> /// Executes an availability test for a Url /// </summary> /// <param name="log"></param> /// <param name="testName"></param> /// <param name="uri"></param> /// <returns></returns> private async static Task RunAvailbiltyTestAsync(ILogger log, HttpClient client, AvailabilityTest test, EndPoint endpoint, TelemetryClient telemetryClient) { if (null == test) { Exception ex = new ArgumentOutOfRangeException("test", "The 'test' object is null."); log.LogError($"Invalid Test Settings : {ex.Message}"); throw ex; } if (null == telemetryClient) { Exception ex = new ArgumentOutOfRangeException("telemetryClient", "The 'telemetryClient' object is null."); log.LogError($"Invalid Test Settings : {ex.Message}"); throw ex; } if (null == endpoint) { Exception ex = new ArgumentOutOfRangeException("telemetryClient", "The 'telemetryClient' object is null."); log.LogError($"Invalid Test Settings : {ex.Message}"); throw ex; } if (String.IsNullOrEmpty(endpoint.Name)) { Exception ex = new ArgumentOutOfRangeException("Name", "No 'Name' was provided in the config."); log.LogError($"Invalid Test Settings : {ex.Message}"); throw ex; } Uri goodUri = null; Uri.TryCreate(endpoint.PageUrl, UriKind.Absolute, out goodUri); if (null == goodUri) { Exception ex = new ArgumentOutOfRangeException("uri", $"The provided uri {endpoint.PageUrl} is invalid."); log.LogError($"Invalid Test Settings : {ex.Message}"); throw ex; } //setup the telemetry string operationId = Guid.NewGuid().ToString("N"); var availability = new AvailabilityTelemetry { Id = operationId, Name = $"{test.ApplicationName} : {endpoint.Name}", RunLocation = System.Environment.MachineName, Success = false }; //start the timer var stopwatch = new Stopwatch(); stopwatch.Start(); //try it try { await ExecuteWebGet(log, availability, client, goodUri).ConfigureAwait(false); } catch (HttpRequestException ex) { //grab the inner exception if the Request fails outright availability.Message = ex.InnerException.Message; var exceptionTelemetry = new ExceptionTelemetry(ex); exceptionTelemetry.Context.Operation.Id = operationId; exceptionTelemetry.Properties.Add("TestName", endpoint.Name); exceptionTelemetry.Properties.Add("TestLocation", System.Environment.MachineName); telemetryClient.TrackException(exceptionTelemetry); } catch (Exception ex) { availability.Message = ex.Message; var exceptionTelemetry = new ExceptionTelemetry(ex); exceptionTelemetry.Context.Operation.Id = operationId; exceptionTelemetry.Properties.Add("TestName", endpoint.Name); exceptionTelemetry.Properties.Add("TestLocation", System.Environment.MachineName); telemetryClient.TrackException(exceptionTelemetry); } finally { stopwatch.Stop(); availability.Duration = stopwatch.Elapsed; availability.Timestamp = DateTimeOffset.UtcNow; telemetryClient.TrackAvailability(availability); // call flush to ensure telemetry is sent telemetryClient.Flush(); } }
public void SendEventToValidateEndpoint() { string unicodeString = "русский\\#/\x0000\x0001\x0002\x0003\x0004\x0005\x0006\x0007\x0008\x009Farabicشلاؤيثبلاهتنمةىخحضقسفعشلاؤيصثبل c\n\r\t"; EventTelemetry telemetry1 = new EventTelemetry(unicodeString); MetricTelemetry telemetry2 = new MetricTelemetry("name", 100); DependencyTelemetry telemetry3 = new DependencyTelemetry("name", "commandName", DateTimeOffset.UtcNow, TimeSpan.FromHours(3), true); ExceptionTelemetry telemetry4 = new ExceptionTelemetry(new ArgumentException("Test")); MetricTelemetry telemetry5 = new MetricTelemetry("name", 100); PageViewTelemetry telemetry6 = new PageViewTelemetry("name"); #pragma warning disable 618 PerformanceCounterTelemetry telemetry7 = new PerformanceCounterTelemetry("category", "name", "instance", 100); #pragma warning restore 618 RequestTelemetry telemetry8 = new RequestTelemetry("name", DateTimeOffset.UtcNow, TimeSpan.FromHours(2), "200", true); #pragma warning disable 618 SessionStateTelemetry telemetry9 = new SessionStateTelemetry(SessionState.Start); #pragma warning restore 618 TraceTelemetry telemetry10 = new TraceTelemetry("text"); AvailabilityTelemetry telemetry11 = new AvailabilityTelemetry("name", DateTimeOffset.UtcNow, TimeSpan.FromHours(10), "location", true, "message"); var telemetryItems = new List <ITelemetry> { telemetry1, telemetry2, telemetry3, telemetry4, telemetry5, telemetry6, telemetry7, telemetry8, telemetry9, telemetry10, telemetry11 }; // ChuckNorrisTeamUnitTests resource in Prototypes5 var config = new TelemetryConfiguration("fafa4b10-03d3-4bb0-98f4-364f0bdf5df8"); var telemetryClient = new TelemetryClient(config); telemetryClient.Context.Properties.Add(unicodeString, unicodeString); telemetryClient.Initialize(telemetry1); telemetryClient.Initialize(telemetry2); telemetryClient.Initialize(telemetry3); telemetryClient.Initialize(telemetry4); telemetryClient.Initialize(telemetry5); telemetryClient.Initialize(telemetry6); telemetryClient.Initialize(telemetry7); telemetryClient.Initialize(telemetry8); telemetryClient.Initialize(telemetry9); telemetryClient.Initialize(telemetry10); telemetryClient.Initialize(telemetry11); string json = JsonSerializer.SerializeAsString(telemetryItems); HttpClient client = new HttpClient(); var result = client.PostAsync( "https://dc.services.visualstudio.com/v2/validate", new ByteArrayContent(Encoding.UTF8.GetBytes(json))).GetAwaiter().GetResult(); if (result.StatusCode != HttpStatusCode.OK) { var response = result.Content.ReadAsStringAsync().GetAwaiter().GetResult(); Trace.WriteLine(response); } Assert.Equal(HttpStatusCode.OK, result.StatusCode); }
private static void SerializeTelemetryItem(ITelemetry telemetryItem, JsonWriter jsonWriter) { if (telemetryItem is EventTelemetry) { EventTelemetry eventTelemetry = telemetryItem as EventTelemetry; SerializeEventTelemetry(eventTelemetry, jsonWriter); } else if (telemetryItem is ExceptionTelemetry) { ExceptionTelemetry exceptionTelemetry = telemetryItem as ExceptionTelemetry; SerializeExceptionTelemetry(exceptionTelemetry, jsonWriter); } else if (telemetryItem is MetricTelemetry) { MetricTelemetry metricTelemetry = telemetryItem as MetricTelemetry; SerializeMetricTelemetry(metricTelemetry, jsonWriter); } else if (telemetryItem is PageViewTelemetry) { PageViewTelemetry pageViewTelemetry = telemetryItem as PageViewTelemetry; SerializePageViewTelemetry(pageViewTelemetry, jsonWriter); } else if (telemetryItem is DependencyTelemetry) { DependencyTelemetry remoteDependencyTelemetry = telemetryItem as DependencyTelemetry; SerializeDependencyTelemetry(remoteDependencyTelemetry, jsonWriter); } else if (telemetryItem is RequestTelemetry) { RequestTelemetry requestTelemetry = telemetryItem as RequestTelemetry; SerializeRequestTelemetry(requestTelemetry, jsonWriter); } #pragma warning disable 618 else if (telemetryItem is SessionStateTelemetry) { EventTelemetry telemetry = (telemetryItem as SessionStateTelemetry).Data; SerializeEventTelemetry(telemetry, jsonWriter); } #pragma warning restore 618 else if (telemetryItem is TraceTelemetry) { TraceTelemetry traceTelemetry = telemetryItem as TraceTelemetry; SerializeTraceTelemetry(traceTelemetry, jsonWriter); } #pragma warning disable 618 else if (telemetryItem is PerformanceCounterTelemetry) { MetricTelemetry telemetry = (telemetryItem as PerformanceCounterTelemetry).Data; SerializeMetricTelemetry(telemetry, jsonWriter); } else if (telemetryItem is AvailabilityTelemetry) { AvailabilityTelemetry availabilityTelemetry = telemetryItem as AvailabilityTelemetry; SerializeAvailability(availabilityTelemetry, jsonWriter); } else { string msg = string.Format(CultureInfo.InvariantCulture, "Unknown telemetry type: {0}", telemetryItem.GetType()); CoreEventSource.Log.LogVerbose(msg); } }
private static void SerializeTelemetryItem(ITelemetry telemetryItem, JsonSerializationWriter jsonSerializationWriter) { jsonSerializationWriter.WriteStartObject(); if (telemetryItem is EventTelemetry) { EventTelemetry eventTelemetry = telemetryItem as EventTelemetry; CopyGlobalPropertiesIfExist(telemetryItem.Context, eventTelemetry.Data.properties); SerializeHelper(telemetryItem, jsonSerializationWriter, eventTelemetry.BaseType, EventTelemetry.TelemetryName); } else if (telemetryItem is ExceptionTelemetry) { ExceptionTelemetry exTelemetry = telemetryItem as ExceptionTelemetry; CopyGlobalPropertiesIfExist(telemetryItem.Context, exTelemetry.Data.Data.properties); SerializeHelper(telemetryItem, jsonSerializationWriter, exTelemetry.BaseType, ExceptionTelemetry.TelemetryName); } else if (telemetryItem is MetricTelemetry) { MetricTelemetry mTelemetry = telemetryItem as MetricTelemetry; CopyGlobalPropertiesIfExist(telemetryItem.Context, mTelemetry.Data.properties); SerializeHelper(telemetryItem, jsonSerializationWriter, mTelemetry.BaseType, MetricTelemetry.TelemetryName); } else if (telemetryItem is PageViewTelemetry) { PageViewTelemetry pvTelemetry = telemetryItem as PageViewTelemetry; CopyGlobalPropertiesIfExist(telemetryItem.Context, pvTelemetry.Data.properties); SerializeHelper(telemetryItem, jsonSerializationWriter, pvTelemetry.BaseType, PageViewTelemetry.TelemetryName); } else if (telemetryItem is PageViewPerformanceTelemetry) { PageViewPerformanceTelemetry pvptelemetry = telemetryItem as PageViewPerformanceTelemetry; CopyGlobalPropertiesIfExist(telemetryItem.Context, pvptelemetry.Data.properties); SerializeHelper(telemetryItem, jsonSerializationWriter, PageViewPerformanceTelemetry.BaseType, PageViewPerformanceTelemetry.TelemetryName); } else if (telemetryItem is DependencyTelemetry) { DependencyTelemetry depTelemetry = telemetryItem as DependencyTelemetry; CopyGlobalPropertiesIfExist(telemetryItem.Context, depTelemetry.InternalData.properties); SerializeHelper(telemetryItem, jsonSerializationWriter, depTelemetry.BaseType, DependencyTelemetry.TelemetryName); } else if (telemetryItem is RequestTelemetry) { RequestTelemetry reqTelemetry = telemetryItem as RequestTelemetry; CopyGlobalPropertiesIfExist(telemetryItem.Context, reqTelemetry.Data.properties); SerializeHelper(telemetryItem, jsonSerializationWriter, reqTelemetry.BaseType, RequestTelemetry.TelemetryName); } #pragma warning disable 618 else if (telemetryItem is PerformanceCounterTelemetry) { PerformanceCounterTelemetry pcTelemetry = telemetryItem as PerformanceCounterTelemetry; CopyGlobalPropertiesIfExist(telemetryItem.Context, pcTelemetry.Data.Properties); SerializeHelper(telemetryItem, jsonSerializationWriter, pcTelemetry.Data.BaseType, MetricTelemetry.TelemetryName); } else if (telemetryItem is SessionStateTelemetry) { SessionStateTelemetry ssTelemetry = telemetryItem as SessionStateTelemetry; SerializeHelper(telemetryItem, jsonSerializationWriter, ssTelemetry.Data.BaseType, EventTelemetry.TelemetryName); } #pragma warning restore 618 else if (telemetryItem is TraceTelemetry) { TraceTelemetry traceTelemetry = telemetryItem as TraceTelemetry; CopyGlobalPropertiesIfExist(telemetryItem.Context, traceTelemetry.Data.properties); SerializeHelper(telemetryItem, jsonSerializationWriter, traceTelemetry.BaseType, TraceTelemetry.TelemetryName); } else if (telemetryItem is AvailabilityTelemetry) { AvailabilityTelemetry availabilityTelemetry = telemetryItem as AvailabilityTelemetry; CopyGlobalPropertiesIfExist(telemetryItem.Context, availabilityTelemetry.Data.properties); SerializeHelper(telemetryItem, jsonSerializationWriter, availabilityTelemetry.BaseType, AvailabilityTelemetry.TelemetryName); } else { string msg = string.Format(CultureInfo.InvariantCulture, "Unknown telemetry type: {0}", telemetryItem.GetType()); CoreEventSource.Log.LogVerbose(msg); } jsonSerializationWriter.WriteEndObject(); }
public void Complete(AvailabilityTelemetry availabilityResult) { using (_log.BeginScopeSafe(_logScope)) { _log?.LogInformation($"{nameof(AvailabilityTestScope)}.{nameof(Complete)} beginning:" + " {{TestDisplayName=\"{TestDisplayName}\", SpanId=\"{SpanId}\"}}", TestDisplayName, Format.SpellIfNull(_activitySpanId)); Validate.NotNull(availabilityResult, nameof(availabilityResult)); TransitionStage(from: Stage.Started, to: Stage.Completed); // Stop the timer: _endTime = DateTimeOffset.Now; // Stop activity: _activitySpan.Stop(); // Examine several properties of the Availability Result. // If the user set them, use the user's value. Otherwise, initialize appropriately: if (String.IsNullOrWhiteSpace(availabilityResult.Message)) { availabilityResult.Message = availabilityResult.Success ? DefaultResultMessage_NoError_Pass : DefaultResultMessage_NoError_Fail; } if (availabilityResult.Timestamp == default(DateTimeOffset)) { availabilityResult.Timestamp = _startTime; } else if (availabilityResult.Timestamp.ToUniversalTime() != _startTime.ToUniversalTime()) { _log?.LogDebug($"{nameof(AvailabilityTestScope)}.{nameof(Complete)} (SpanId=\"{{SpanId}}\") detected that the Timestamp of the" + $" specified Availability Result is different from the corresponding value of this {nameof(AvailabilityTestScope)}." + $" The value specified in the Availability Result takes precedence for tracking." + " AvailabilityTestScope_StartTime=\"{AvailabilityTestScope_StartTime}\". AvailabilityResult_Timestamp=\"{AvailabilityResult_Timestamp}\"", _activitySpanId, _startTime.ToUniversalTime().ToString("o"), availabilityResult.Timestamp.ToUniversalTime().ToString("o")); } TimeSpan duration = _endTime - availabilityResult.Timestamp; if (availabilityResult.Duration == TimeSpan.Zero) { availabilityResult.Duration = duration; } else if (availabilityResult.Duration != duration) { _log?.LogDebug($"{nameof(AvailabilityTestScope)}.{nameof(Complete)} (SpanId=\"{{SpanId}}\") detected that the Duration of the" + $" specified Availability Result is different from the corresponding value of this {nameof(AvailabilityTestScope)}." + $" The value specified in the Availability Result takes precedence for tracking." + " AvailabilityTestScope_Duration=\"{AvailabilityTestScope_Duration}\". AvailabilityResult_Duration=\"{AvailabilityResult_Duration}\"", _activitySpanId, duration, availabilityResult.Duration); } if (String.IsNullOrWhiteSpace(availabilityResult.Name)) { availabilityResult.Name = this.TestDisplayName; } else if (!availabilityResult.Name.Equals(TestDisplayName, StringComparison.Ordinal)) { _log?.LogDebug($"{nameof(AvailabilityTestScope)}.{nameof(Complete)} (SpanId=\"{{SpanId}}\") detected that the Name of the" + $" specified Availability Result is different from the corresponding value of this {nameof(AvailabilityTestScope)}." + $" The value specified in the Availability Result takes precedence for tracking." + " AvailabilityTestScopeTestDisplayName=\"{AvailabilityTestScope_TestDisplayName}\". AvailabilityResult_Name=\"{AvailabilityResult_Name}\"", _activitySpanId, TestDisplayName, availabilityResult.Name); } if (String.IsNullOrWhiteSpace(availabilityResult.RunLocation)) { availabilityResult.RunLocation = this.LocationDisplayName; } else if (!availabilityResult.RunLocation.Equals(LocationDisplayName, StringComparison.Ordinal)) { _log?.LogDebug($"{nameof(AvailabilityTestScope)}.{nameof(Complete)} (SpanId=\"{{SpanId}}\") detected that the RunLocation of the" + $" specified Availability Result is different from the corresponding value of this {nameof(AvailabilityTestScope)}." + $" The value specified in the Availability Result takes precedence for tracking." + " AvailabilityTestScope_LocationDisplayName=\"{AvailabilityTestScope_LocationDisplayName}\". AvailabilityResult_RunLocation=\"{AvailabilityResult_RunLocation}\"", _activitySpanId, LocationDisplayName, availabilityResult.RunLocation); } // The user may or may not have set the ID of the availability result telemetry. // Either way, we must set it to the right value, otherwise distributed tracing will break: availabilityResult.Id = _activitySpanId; // Similarly, whatever iKey the user set, we insist on the value from this scope's telemetry configuration to make // sure everything ends up in the right place. // Users may request a feature to allow sending availabuility results to an iKey that is different from other telemetry. // If so, we should consider exposing a corresponsing parameter on the ctor of this class and - corresponsingly - on // the AvailabilityTestResultAttribute. In that case we must also do the appropriate thing with the traces sent by this // class. Sending them and the telemetry result to different destinations may be a failure pit for the user. availabilityResult.Context.InstrumentationKey = _instrumentationKey; // Set custom SDK version to differentiate CAT tests from the regular availability telemetry availabilityResult.Context.GetInternalContext().SdkVersion = SdkVersion; // Store the result, but do not send it until SendResult() is called: _finalAvailabilityResult = availabilityResult; _log?.LogInformation($"{nameof(AvailabilityTestScope)}.{nameof(Complete)} finished" + " {{TestDisplayName=\"{TestDisplayName}\", " + " SpanId=\"{SpanId}\", StartTime=\"{StartTime}\", EndTime=\"{EndTime}\", Duration=\"{Duration}\", Success=\"{Success}\"}}", TestDisplayName, _activitySpanId, _startTime.ToString("o"), _endTime.ToString("o"), duration, availabilityResult.Success); } }
private void AddAvailabilityProperties(IDictionary <string, object> eventPayload, AvailabilityTelemetry availability) { eventPayload.Add(TelemetryTypeProperty, "availability"); eventPayload.Add(nameof(availability.Name), availability.Name); if (!string.IsNullOrEmpty(availability.Id)) { eventPayload.Add(nameof(availability.Id), availability.Id); } if (availability.Duration != TimeSpan.Zero) { eventPayload.Add(nameof(availability.Duration), availability.Duration); } eventPayload.Add(nameof(availability.Success), availability.Success); if (!string.IsNullOrEmpty(availability.RunLocation)) { eventPayload.Add(nameof(availability.RunLocation), availability.RunLocation); } if (!string.IsNullOrEmpty(availability.Message)) { eventPayload.Add(nameof(availability.Message), availability.Message); } }
private async Task <ActionResult <ResultAccountGetSinnersByAuthorization> > GetSINnersByAuthorizationInternal() { Stopwatch sw = new Stopwatch(); sw.Start(); //var tc = new Microsoft.ApplicationInsights.TelemetryClient(); ResultAccountGetSinnersByAuthorization res = null; SINSearchGroupResult ret = new SINSearchGroupResult(); res = new ResultAccountGetSinnersByAuthorization(ret); SINnerGroup sg = new SINnerGroup(); var user = await _signInManager.UserManager.GetUserAsync(User); if (user == null) { var e = new AuthenticationException("User is not authenticated."); res = new ResultAccountGetSinnersByAuthorization(e) { ErrorText = "Unauthorized" }; return(BadRequest(res)); } user.FavoriteGroups = user.FavoriteGroups.GroupBy(a => a.FavoriteGuid).Select(b => b.First()).ToList(); SINnerSearchGroup ssg = new SINnerSearchGroup(sg, user) { MyMembers = new List <SINnerSearchGroupMember>() }; using (var t = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = IsolationLevel.ReadUncommitted }, TransactionScopeAsyncFlowOption.Enabled)) { try { var roles = await _userManager.GetRolesAsync(user); ret.Roles = roles.ToList(); ssg.Groupname = user.UserName; ssg.Id = Guid.Empty; var worklist = user.FavoriteGroups.Select(a => a.FavoriteGuid).ToList(); var groupworklist = _context.SINnerGroups .Include(a => a.MyGroups) .ThenInclude(b => b.MyGroups) .ThenInclude(c => c.MyGroups) .ThenInclude(d => d.MyGroups) .Where(a => a.Id != null && worklist.Contains(a.Id.Value)).ToList(); ssg.MySINSearchGroups = await RecursiveBuildGroupMembers(groupworklist, user); var memberworklist = _context.SINners .Include(a => a.MyGroup) .Include(a => a.SINnerMetaData.Visibility) .Where(a => a.Id != null && worklist.Contains(a.Id.Value)); foreach (var member in memberworklist) { if (member.SINnerMetaData?.Visibility?.IsGroupVisible == false) { if (member.SINnerMetaData?.Visibility.UserRights.Any(a => !string.IsNullOrEmpty(a.EMail)) == true) { if (member.SINnerMetaData?.Visibility.UserRights.Any(a => user.NormalizedEmail.Equals(a.EMail, StringComparison.OrdinalIgnoreCase)) == false) { //dont show this guy! continue; } } } member.LastDownload = DateTime.Now; if (member.MyGroup == null) { member.MyGroup = new SINnerGroup(); } if (member.MyGroup.MyGroups == null) { member.MyGroup.MyGroups = new List <SINnerGroup>(); } SINnerSearchGroupMember sinssgGroupMember = new SINnerSearchGroupMember(user, member) { MySINner = member }; ssg.MyMembers.Add(sinssgGroupMember); } await _context.SaveChangesAsync(); ret.SINGroups.Add(ssg); res = new ResultAccountGetSinnersByAuthorization(ret); return(Ok(res)); } catch (Exception e) { try { await _signInManager.UserManager.GetUserAsync(User); ExceptionTelemetry et = new ExceptionTelemetry(e); et.Properties.Add("user", User.Identity.Name); tc.TrackException(et); } catch (Exception ex) { _logger?.LogError(ex.ToString()); } res = new ResultAccountGetSinnersByAuthorization(e); return(BadRequest(res)); } finally { AvailabilityTelemetry telemetry = new AvailabilityTelemetry("GetSINnersByAuthorization", DateTimeOffset.Now, sw.Elapsed, "Azure", res.CallSuccess, res.ErrorText); tc?.TrackAvailability(telemetry); } } }
private static async Task TestAvailability(TelemetryClient telemetryClient, HttpClient HttpClient, String address, ILogger _logger) { var availability = new AvailabilityTelemetry { Id = Guid.NewGuid().ToString(), Name = $"Availability Test: {address}", RunLocation = System.Environment.MachineName, Success = false }; var stopwatch = new Stopwatch(); stopwatch.Start(); bool isMonitoringFailure = false; try { using (var httpResponse = await HttpClient.GetAsync(address)) { // add test results to availability telemetry property availability.Properties.Add("HttpResponseStatusCode", Convert.ToInt32(httpResponse.StatusCode).ToString()); // check if response content contains specific text string content = httpResponse.Content != null ? await httpResponse.Content.ReadAsStringAsync() : ""; if (httpResponse.IsSuccessStatusCode) { availability.Success = true; availability.Message = $"Test succeeded with response: {httpResponse.StatusCode}"; _logger.LogTrace($"[Verbose]: {availability.Message}"); } else if (!httpResponse.IsSuccessStatusCode) { availability.Message = $"Test failed with response: {httpResponse.StatusCode}"; _logger.LogWarning($"[Warning]: {availability.Message}"); } } } catch (TaskCanceledException e) { availability.Message = $"Test timed out: {e.Message}"; _logger.LogDebug($"[Warning]: {availability.Message}"); } catch (Exception ex) { // track exception when unable to determine the state of web app isMonitoringFailure = true; var exceptionTelemetry = new ExceptionTelemetry(ex); exceptionTelemetry.Context.Operation.Id = "test"; exceptionTelemetry.Properties.Add("TestName", "test"); exceptionTelemetry.Properties.Add("TestLocation", "test"); exceptionTelemetry.Properties.Add("TestUri", "test"); telemetryClient.TrackException(exceptionTelemetry); _logger.LogError($"[Error]: {ex.Message}"); // optional - throw to fail the function throw; } finally { stopwatch.Stop(); availability.Duration = stopwatch.Elapsed; availability.Timestamp = DateTimeOffset.UtcNow; // do not make an assumption as to the state of the web app when monitoring failures occur if (!isMonitoringFailure) { telemetryClient.TrackAvailability(availability); _logger.LogInformation($"Availability telemetry for {availability.Name} is sent."); } // call flush to ensure telemetries are sent telemetryClient.Flush(); } }
private static void RunCustomAIAvailabilityTest(ILogger log) { log.LogInformation($"Entering Run at: {DateTime.Now}"); // [CONFIGURATION_REQUIRED] provide {testName} accordingly for your test function string testName = "AvailabilityTestConsole"; // REGION_NAME is a default environment variable that comes with App Service string location = "Boston, MA"; //"East US"; //Environment.GetEnvironmentVariable("REGION_NAME"); log.LogInformation($"Executing availability test run for {testName} at: {DateTime.Now}"); string operationId = Guid.NewGuid().ToString("N"); Console.WriteLine("Enter: 1 for Github Test, 2 for local Test, other for null Test"); int i = Convert.ToInt32(Console.ReadLine()); var availability = new AvailabilityTelemetry { Id = operationId, Name = testName, RunLocation = location, Success = false }; var stopwatch = new Stopwatch(); stopwatch.Start(); try { switch (i) { case 1: availability.Properties.Add("Test Url", "https://api.github.com/orgs/dotnet/repos"); RunAvailabilityTestGithubDotnet(log); break; case 2: RunAvailabilityTestLocal(log); availability.Properties.Add("Test Url", "http://localhost:5555/"); break; default: RunNotImplemented(log); break; } availability.Success = true; availability.Message = "Availability test from Console"; availability.Properties.Add("Server", "JuanLaptop"); } catch (Exception ex) { availability.Message = ex.Message; availability.Success = false; var exceptionTelemetry = new ExceptionTelemetry(ex); exceptionTelemetry.Context.Operation.Id = operationId; exceptionTelemetry.Properties.Add("TestName", testName); exceptionTelemetry.Properties.Add("TestLocation", location); telemetryClient.TrackException(exceptionTelemetry); } finally { stopwatch.Stop(); availability.Duration = stopwatch.Elapsed; availability.Timestamp = DateTimeOffset.UtcNow; telemetryClient.TrackAvailability(availability); // call flush to ensure telemetry is sent telemetryClient.Flush(); } }
private static async Task TestAvailability(TelemetryClient telemetryClient, HttpClient client, String address, ILogger _logger) { var availability = new AvailabilityTelemetry { Id = Guid.NewGuid().ToString("N"), Name = address, RunLocation = System.Environment.MachineName, Success = false }; string testRunId = availability.Id; availability.Context.Operation.Id = availability.Id; var stopwatch = new Stopwatch(); stopwatch.Start(); DateTimeOffset startTimeTest = DateTimeOffset.UtcNow; try { var request = new HttpRequestMessage() { RequestUri = new Uri(address), Method = HttpMethod.Get }; request.Headers.Add("SyntheticTest-RunId", testRunId); request.Headers.Add("Request-Id", "|" + testRunId); using (var httpResponse = await client.SendAsync(request).ConfigureAwait(false)) { // add test results to availability telemetry property availability.Properties.Add("HttpResponseStatusCode", Convert.ToInt32(httpResponse.StatusCode).ToString()); if (httpResponse.IsSuccessStatusCode) { availability.Success = true; availability.Message = $"Test succeeded with response: {httpResponse.StatusCode}"; _logger.LogTrace($"[Verbose]: {availability.Message}"); } else if (!httpResponse.IsSuccessStatusCode) { availability.Message = $"Test failed with response: {httpResponse.StatusCode}"; _logger.LogWarning($"[Warning]: {availability.Message}"); } } } catch (Exception ex) { // track exception when unable to determine the state of web app availability.Message = ex.Message; var exceptionTelemetry = new ExceptionTelemetry(ex); exceptionTelemetry.Context.Operation.Id = availability.Id; exceptionTelemetry.Properties.Add("TestAddress", address); exceptionTelemetry.Properties.Add("RunLocation", availability.RunLocation); telemetryClient.TrackException(exceptionTelemetry); _logger.LogError($"[Error]: {ex.Message}"); } finally { stopwatch.Stop(); availability.Duration = stopwatch.Elapsed; availability.Timestamp = startTimeTest; telemetryClient.TrackAvailability(availability); _logger.LogInformation($"Availability telemetry for {availability.Name} is sent."); } }
private static async Task TestAvailability(TelemetryClient telemetryClient, HttpClient HttpClient, String address, ILogger _logger) { var availability = new AvailabilityTelemetry { Id = Guid.NewGuid().ToString(), Name = address, RunLocation = System.Environment.MachineName, Success = false }; var stopwatch = new Stopwatch(); stopwatch.Start(); bool isMonitoringFailure = false; try { using (var httpResponse = await HttpClient.GetAsync(address)) { // add test results to availability telemetry property availability.Properties.Add("HttpResponseStatusCode", Convert.ToInt32(httpResponse.StatusCode).ToString()); //if HttpStatusCode is in the successful range 200-299 if (httpResponse.IsSuccessStatusCode) { availability.Success = true; availability.Message = $"Test succeeded with response: {httpResponse.StatusCode}"; _logger.LogTrace($"[Verbose]: {availability.Message}"); } else if (!httpResponse.IsSuccessStatusCode) { availability.Message = $"Test failed with response: {httpResponse.StatusCode}"; _logger.LogWarning($"[Warning]: {availability.Message}"); } } } catch (System.Net.Sockets.SocketException se) { availability.Message = $"Test failed with socket exception, response: {se.Message}"; _logger.LogWarning($"[Warning]: {availability.Message}"); } catch (TaskCanceledException e) { availability.Message = $"Test failed due to monitoring interruption: {e.Message}"; _logger.LogWarning($"[Warning]: {availability.Message}"); } catch (System.Net.Http.HttpRequestException hre) { availability.Message = $"Test failed with an HTTP request exception, response: {hre.Message}"; _logger.LogWarning($"[Warning]: {availability.Message}"); } catch (Exception ex) { // track exception when unable to determine the state of web app isMonitoringFailure = true; var exceptionTelemetry = new ExceptionTelemetry(ex); // exceptionTelemetry.Context.Operation.Id = "test"; exceptionTelemetry.Properties.Add("Message", ex.Message); exceptionTelemetry.Properties.Add("Source", ex.Source); exceptionTelemetry.Properties.Add("Test site", address); //exceptionTelemetry.Properties.Add("StackTrace", ex.StackTrace); telemetryClient.TrackException(exceptionTelemetry); _logger.LogError($"[Error]: {ex.Message}"); } finally { stopwatch.Stop(); availability.Duration = stopwatch.Elapsed; availability.Timestamp = DateTimeOffset.UtcNow; if (!isMonitoringFailure) { telemetryClient.TrackAvailability(availability); _logger.LogInformation($"Availability telemetry for {availability.Name} is sent."); Console.WriteLine($"Availability telemetry for {availability.Name} is sent."); } // call flush to ensure all telemetry is sent telemetryClient.Flush(); } }
private static async Task TestAvailabilityPing(TelemetryClient telemetryClient, string address, string ikey, ILogger _logger) { var availability = new AvailabilityTelemetry { Id = Guid.NewGuid().ToString("N"), Name = address, RunLocation = System.Environment.MachineName, Success = false }; string testRunId = availability.Id; availability.Context.InstrumentationKey = ikey; availability.Context.Cloud.RoleName = "minion"; availability.Context.Operation.Id = availability.Id; var stopwatch = new Stopwatch(); stopwatch.Start(); DateTimeOffset startTimeTest = DateTimeOffset.UtcNow; Ping sender = new Ping(); PingOptions options = new PingOptions { DontFragment = true }; byte[] buffer = Encoding.ASCII.GetBytes("test test test 1 2 3 4 5 6 7 8 9"); // array of 32 bytes int timeout = 4000; // 4000 milliseconds = 4 seconds try { var reply = await sender.SendPingAsync(address, timeout, buffer, options).ConfigureAwait(false); { if (reply.Status == IPStatus.Success) { // add test results to availability telemetry property availability.Success = true; availability.Message = $"Test succeeded with response: {reply.Status}"; availability.Properties.Add("RoundTrip time", reply.RoundtripTime.ToString()); availability.Properties.Add("Time to live", reply.Options.Ttl.ToString()); _logger.LogTrace($"[Verbose]: {availability.Message}"); } else { availability.Message = "Ping test failed."; _logger.LogWarning($"[Warning]: {availability.Message}"); } } } catch (Exception ex) { // track exception when unable to get ping status availability.Message = ex.Message; var exceptionTelemetry = new ExceptionTelemetry(ex); exceptionTelemetry.Context.InstrumentationKey = ikey; exceptionTelemetry.Context.Cloud.RoleName = "minion"; exceptionTelemetry.Context.Operation.Id = availability.Id; exceptionTelemetry.Properties.Add("TestAddress", address); exceptionTelemetry.Properties.Add("RunLocation", availability.RunLocation); telemetryClient.TrackException(exceptionTelemetry); _logger.LogError($"[Error]: {ex.Message}"); } finally { stopwatch.Stop(); availability.Duration = stopwatch.Elapsed; availability.Timestamp = startTimeTest; telemetryClient.TrackAvailability(availability); _logger.LogInformation($"Availability telemetry for {availability.Name} is sent."); sender.Dispose(); } }
public static async Task RunAsync([TimerTrigger("0 */5 * * * *")] TimerInfo myTimer, ILogger log) { log.LogInformation($"Entering Run at: {DateTime.Now}"); if (myTimer.IsPastDue) { log.LogWarning($"[Warning]: Timer is running late! Last ran at: {myTimer.ScheduleStatus.Last}"); } log.LogInformation($"Executing availability test run for {testName} at: {DateTime.Now}"); string operationId = Guid.NewGuid().ToString("N"); var availability = new AvailabilityTelemetry { Id = operationId, Name = testName, RunLocation = location, Success = false }; log.LogInformation($"Telemetry data : {operationId}, {testName} , {location} , {instrumentationKey}"); var stopwatch = new Stopwatch(); stopwatch.Start(); var telemetry = new TraceTelemetry(); try { bool success = await RunAvailbiltyTestAsync(log); if (success) { availability.Message = $"The health check for {Url} passed successfully "; } else if (!success) { string failedurl = " "; failedUrls = failedUrls.Distinct().ToList(); foreach (string url in failedUrls) { failedurl = failedurl + url + ","; } availability.Message = "health check failed for following urls' " + failedurl; } availability.Success = success; } catch (Exception ex) { availability.Message = ex.Message; var exceptionTelemetry = new ExceptionTelemetry(ex); exceptionTelemetry.Context.Operation.Id = operationId; exceptionTelemetry.Properties.Add("TestName", testName); exceptionTelemetry.Properties.Add("TestLocation", location); telemetryClient.TrackException(exceptionTelemetry); log.LogError($"[Error]: The monitoring custom code failed with exception , { ex.Message}"); } finally { stopwatch.Stop(); availability.Duration = stopwatch.Elapsed; availability.Timestamp = DateTimeOffset.UtcNow; telemetryClient.TrackAvailability(availability); // call flush to ensure telemetry is sent telemetryClient.Flush(); } }
public void LogAvailability(AvailabilityTelemetry telemetry) => client.TrackAvailability(telemetry);