protected override T Intercept <T>(IInvocation invocation, Func <T> call) { using (ILifetimeScope scope = _outerScope.BeginLifetimeScope(_configureScope)) { var client = scope.Resolve <TelemetryClient>(); var context = scope.Resolve <ServiceContext>(); string url = $"{context.ServiceName}/{invocation.Method?.DeclaringType?.Name}/{invocation.Method?.Name}"; using (IOperationHolder <RequestTelemetry> op = client.StartOperation <RequestTelemetry>($"RPC {url}")) { try { op.Telemetry.Url = new Uri(url); object instance = scope.Resolve(_implementationType); ((IChangeProxyTarget)invocation).ChangeInvocationTarget(instance); return(call()); } catch (Exception ex) { op.Telemetry.Success = false; client.TrackException(ex); throw; } } } }
public static TimeSpan Finish(string taskname, IOperationHolder <DependencyTelemetry> telemetry) { if (s_DictionaryStarts.TryRemove(taskname, out TimeSpan objStartTimeSpan)) { TimeSpan final = s_Time.Elapsed - objStartTimeSpan; string logentry = $"Task \"{taskname}\" finished in {final}"; if (telemetry?.Telemetry?.Properties != null) { telemetry.Telemetry.Properties.Add(taskname, final.ToString()); } Logger.Info(logentry); Debug.WriteLine(logentry); if (s_DictionaryStatistics.TryGetValue(taskname, out Tuple <TimeSpan, int> existing)) { s_DictionaryStatistics[taskname] = new Tuple <TimeSpan, int>(existing.Item1 + final, existing.Item2 + 1); } else { s_DictionaryStatistics.TryAdd(taskname, new Tuple <TimeSpan, int>(final, 1)); } return(final); } else { Debug.WriteLine("Non started task \"" + taskname + "\" finished"); return(TimeSpan.Zero); } }
private void UpdateTelemetryOperationContext(Headers headers, IOperationHolder <RequestTelemetry> operation = null) { if (operation == null) { return; } var traceparentHeader = headers.FirstOrDefault(h => h.Key == HeaderNames.TraceParent); if (traceparentHeader != null) { var traceparent = Encoding.UTF8.GetString(traceparentHeader.GetValueBytes()); if (!operation.Telemetry.Context.TrySetOperationContextFromTraceparent(traceparent)) { _logger.LogWarning($"Skipping update of the operation context. Review traceparent format, received {traceparent}"); return; } } var tracestateHeader = headers.FirstOrDefault(h => h.Key == HeaderNames.TraceState); if (tracestateHeader != null) { var tracestate = Encoding.UTF8.GetString(tracestateHeader.GetValueBytes()); Activity.Current.SetTraceContextWithTracestate(tracestate); } }
public NextOperation(int index, SyntaxToken token1, SyntaxToken token2, IOperationHolder <TResult> operationCache) { this.index = index; this.token1 = token1; this.token2 = token2; this.operationCache = operationCache; }
protected override async Task <T> InterceptAsync <T>(IInvocation invocation, Func <Task <T> > call) { var actor = (Actor)invocation.Proxy; using (IServiceScope scope = _outerScope.CreateScope()) { var client = scope.ServiceProvider.GetRequiredService <TelemetryClient>(); var context = scope.ServiceProvider.GetRequiredService <ServiceContext>(); ActorId id = actor.Id; string url = $"{context.ServiceName}/{id}/{invocation.Method?.DeclaringType?.Name}/{invocation.Method?.Name}"; using (IOperationHolder <RequestTelemetry> op = client.StartOperation <RequestTelemetry>($"RPC {url}")) { try { op.Telemetry.Url = new Uri(url); TActor a = scope.ServiceProvider.GetRequiredService <TActor>(); a.Initialize(actor.Id, actor.StateManager, actor as IReminderManager); invocation.ReturnValue = a; return(await call()); } catch (Exception ex) { op.Telemetry.Success = false; client.TrackException(ex); throw; } } } }
protected override void EndReport(string contextName) { base.EndReport(contextName); Client.Context.Properties.Remove("MetricsReportContext"); Client.StopOperation(Operation); Operation = null; }
public static void StartOperation(IOperationHolder <RequestTelemetry> aiOperationHolder) { OperationHolder.Current = new OperationHolder() { AIOperationHolder = aiOperationHolder }; }
protected override async Task <T> InterceptAsync <T>(IInvocation invocation, Func <Task <T> > call) { using (IServiceScope scope = _outerScope.CreateScope()) { var client = scope.ServiceProvider.GetRequiredService <TelemetryClient>(); var context = scope.ServiceProvider.GetRequiredService <ServiceContext>(); string url = $"{context.ServiceName}/{invocation.Method?.DeclaringType?.Name}/{invocation.Method?.Name}"; using (IOperationHolder <RequestTelemetry> op = client.StartOperation <RequestTelemetry>($"RPC {url}")) { try { op.Telemetry.Url = new Uri(url); var instance = scope.ServiceProvider.GetRequiredService <TService>(); _configureScope(instance); ((IChangeProxyTarget)invocation).ChangeInvocationTarget(instance); return(await call()); } catch (Exception ex) { op.Telemetry.Success = false; client.TrackException(ex); throw; } } } }
private void LogFunctionResult(IEnumerable <KeyValuePair <string, object> > state, LogLevel logLevel, Exception exception) { IDictionary <string, object> scopeProps = DictionaryLoggerScope.GetMergedStateDictionary() ?? new Dictionary <string, object>(); // log associated exception details KeyValuePair <string, object>[] stateProps = state as KeyValuePair <string, object>[] ?? state.ToArray(); if (exception != null) { LogException(logLevel, stateProps, exception, null); } ApplyFunctionResultActivityTags(stateProps, scopeProps); IOperationHolder <RequestTelemetry> requestOperation = scopeProps.GetValueOrDefault <IOperationHolder <RequestTelemetry> >(OperationContext); if (requestOperation != null) { // We somehow never started the operation, perhaps, it was auto-tracked by the AI SDK // so there's no way to complete it. RequestTelemetry requestTelemetry = requestOperation.Telemetry; requestTelemetry.Success = exception == null; requestTelemetry.ResponseCode = "0"; // Note: we do not have to set Duration, StartTime, etc. These are handled by the call to Stop() _telemetryClient.StopOperation(requestOperation); } }
private void StartTelemetryIfFunctionInvocation(IDictionary <string, object> stateValues) { if (stateValues == null) { return; } // Http and ServiceBus triggers are tracked automatically by the ApplicationInsights SDK // In such case a current Activity is present. // We won't track and only stamp function specific details on the RequestTelemtery // created by SDK via Activity when function ends if (Activity.Current == null) { string functionName = stateValues.GetValueOrDefault <string>(ScopeKeys.FunctionName); string functionInvocationId = stateValues.GetValueOrDefault <string>(ScopeKeys.FunctionInvocationId); string eventName = stateValues.GetValueOrDefault <string>(ScopeKeys.Event); // If we have the invocation id, function name, and event, we know it's a new function. That means // that we want to start a new operation and let App Insights track it for us. if (!string.IsNullOrEmpty(functionName) && !string.IsNullOrEmpty(functionInvocationId) && eventName == LogConstants.FunctionStartEvent) { RequestTelemetry request = new RequestTelemetry() { Name = functionName }; // We'll need to store this operation context so we can stop it when the function completes IOperationHolder <RequestTelemetry> operation = _telemetryClient.StartOperation(request); stateValues[OperationContext] = operation; } } }
protected override T Intercept <T>(IInvocation invocation, Func <T> call) { var actor = (Actor)invocation.Proxy; using (ILifetimeScope scope = _outerScope.BeginLifetimeScope(builder => ConfigureScope(actor, builder))) { var client = scope.Resolve <TelemetryClient>(); var context = scope.Resolve <ServiceContext>(); ActorId id = actor.Id; string url = $"{context.ServiceName}/{id}/{invocation.Method?.DeclaringType?.Name}/{invocation.Method?.Name}"; using (IOperationHolder <RequestTelemetry> op = client.StartOperation <RequestTelemetry>($"RPC {url}")) { try { op.Telemetry.Url = new Uri(url); invocation.ReturnValue = scope.Resolve(_implementationType); return(call()); } catch (Exception ex) { op.Telemetry.Success = false; client.TrackException(ex); throw; } } } }
/// <summary> /// Starts the Application Insights logging functionality /// Note: this should be set on application startup once /// and will not fire multiple times. /// </summary> public static void InitializeLogging() { try { if (Configuration.System.SendTelemetry && Telemetry.UseApplicationInsights && AppInsights == null) { AppInsights = new TelemetryClient { InstrumentationKey = Telemetry.Key }; AppInsights.Context.Session.Id = Guid.NewGuid().ToString(); AppInsights.Context.Component.Version = GetVersion(); AppRunTelemetry = AppInsights.StartOperation <RequestTelemetry>( $"{GetVersion()} - {Configuration.ApplicationUpdates.AccessCount + 1} - {(UnlockKey.IsAppRegistered() ? "registered" : "unregistered")}"); AppRunTelemetry.Telemetry.Start(); } } catch (Exception ex) { Telemetry.UseApplicationInsights = false; LogLocal("Application Insights initialization failure: " + ex.GetBaseException().Message); } }
private EnvelopedMessage( IEnumerable <byte> body, IMessageConsumer consumer, DateTime createdOn, string correlationId, ulong deliveryTag, string exchange, Guid id, int retryCount, string routingKey, IOperationHolder <RequestTelemetry> telemetryOperation) { _consumer = consumer; _createdOn = createdOn; _deliveryTag = deliveryTag; Body = body.ToImmutableArray(); CorrelationId = correlationId; Exchange = exchange; Id = id; RetryCount = retryCount; RoutingKey = routingKey; _telemetryOperation = telemetryOperation; }
internal IDisposable StartActivityOperation <TOperation>( string name, string operationId = null, string parentOperationId = null, string globalOperationId = null) where TOperation : OperationTelemetry, new() { Util.EnsureNotNull(name, nameof(name)); DistributedTracingActivity currentOperationContext = DistributedTracingActivity.Current; TOperation operation = new TOperation(); operation.Name = name; operation.Id = operationId; if (operation.Id == null) { operation.GenerateOperationId(); } operation.Context.Operation.ParentId = parentOperationId ?? currentOperationContext?.Id; operation.Context.Operation.Id = globalOperationId ?? currentOperationContext?.RootId; operation.Context.Operation.Name = name; IOperationHolder <TOperation> startedOperation = _applicationInsightsClient.StartOperation(operation); return(startedOperation); }
protected override async Task <T> InterceptAsync <T>(IInvocation invocation, Func <Task <T> > call) { string methodName = $"/{invocation.Method?.DeclaringType?.Name}/{invocation.Method?.Name}"; using (IOperationHolder <DependencyTelemetry> op = TelemetryClient.StartOperation <DependencyTelemetry>($"RPC {ServiceUri}{methodName}")) { try { Activity.Current.AddBaggage("CallingServiceName", $"\"{Context.ServiceName.ToString()}\""); op.Telemetry.Type = "ServiceFabricRemoting"; op.Telemetry.Target = ServiceUri; op.Telemetry.Data = ServiceUri + methodName; return(await call()); } catch (Exception ex) { op.Telemetry.Success = false; if (ex is AggregateException ae && ae.InnerExceptions.Count == 1) { ex = ae; } TelemetryClient.TrackException(ex); ExceptionDispatchInfo.Capture(ex).Throw(); // throw; is Required by the compiler because it doesn't know that ExceptionDispatchInfo.Throw throws // ReSharper disable once HeuristicUnreachableCode throw; } } }
protected override async Task InterceptAsync(IInvocation invocation, Func <Task> call) { string methodName = $"/{invocation.Method?.DeclaringType?.Name}/{invocation.Method?.Name}"; using (IOperationHolder <DependencyTelemetry> op = TelemetryClient.StartOperation <DependencyTelemetry>($"RPC {ServiceUri}{methodName}")) { try { Activity.Current.AddBaggage("CallingServiceName", $"\"{Context.ServiceName.ToString()}\""); op.Telemetry.Type = "ServiceFabricRemoting"; op.Telemetry.Target = ServiceUri; op.Telemetry.Data = ServiceUri + methodName; await call(); } catch (Exception ex) { op.Telemetry.Success = false; if (ex is AggregateException ae && ae.InnerExceptions.Count == 1) { ex = ae.InnerExceptions[0]; } TelemetryClient.TrackException(ex); ExceptionDispatchInfo.Capture(ex).Throw(); } } }
public NextOperation(int index, SyntaxToken token1, SyntaxToken token2, IOperationHolder <TResult> operationCache) { _index = index; _token1 = token1; _token2 = token2; _operationCache = operationCache; }
public async Task ApplicationInsights_OuterRequestIsTrackedOnce() { string testName = nameof(TestApplicationInsightsInformation); using (IHost host = ConfigureHost()) { TelemetryClient telemetryClient = host.Services.GetService <TelemetryClient>(); await host.StartAsync(); MethodInfo methodInfo = GetType().GetMethod(testName, BindingFlags.Public | BindingFlags.Static); RequestTelemetry outerRequest = null; // simulate auto tracked HTTP incoming call using (IOperationHolder <RequestTelemetry> operation = telemetryClient.StartOperation <RequestTelemetry>("GET /")) { outerRequest = operation.Telemetry; outerRequest.Success = true; await host.GetJobHost().CallAsync(methodInfo, new { input = "input" }); } await host.StopAsync(); // Validate the request // There must be only one reported by the AppInsights request collector RequestTelemetry[] requestTelemetries = _channel.Telemetries.OfType <RequestTelemetry>().ToArray(); Assert.Single(requestTelemetries); RequestTelemetry functionRequest = requestTelemetries.Single(); Assert.Same(outerRequest, functionRequest); ValidateRequest(functionRequest, testName, true); } }
public void SetDataNullHolder() { IOperationHolder <DependencyTelemetry> holder = null; // ReSharper disable once ExpressionIsAlwaysNull holder.SetData(null, null); Assert.IsNull(holder); }
public IOperationHolder <RequestTelemetry> StartTrackRequest(string requestName) { var operation = _telemetry.StartOperation <RequestTelemetry>(requestName); operation.Telemetry.Start(); internalOperation = operation; return(operation); }
public double GetValueOfPi() { TelemetryClient client = new TelemetryClient(TelemetryConfiguration.Active); IOperationHolder <DependencyTelemetry> holder = client.StartOperation <DependencyTelemetry>("Custom operation from Internal service"); client.TrackEvent("Custom event from Internal service"); client.StopOperation <DependencyTelemetry>(holder); return(3.14d); }
public AnalyticService(RequestTelemetry requestTelemetry) { _telemetryClient.InstrumentationKey = Environment.GetEnvironmentVariable("APP_INSIGHTS_KEY"); _requestTelemetry = requestTelemetry; // start tracking request operation _operation = _telemetryClient.StartOperation(_requestTelemetry); }
public OperationScope(Activity activity, TelemetryClient telemetryClient = null) { Ensure.That(activity).IsNotNull(); this.telemetryClient = telemetryClient; if (this.telemetryClient != null) { requestOperation = this.telemetryClient.StartOperation <RequestTelemetry>(activity); } }
/// <summary> /// Adds operationHold in MemoryCache. DO NOT call it for the request that already exists in the cache. /// This is a known Memory Cache race-condition issue when items with same id are added concurrently /// and MemoryCache leaks memory. It should be fixed sometime AFTER .NET 4.7.1. /// </summary> public void Store(IServiceRemotingRequestMessage key, IOperationHolder <T> operationHolder) { if (operationHolder == null) { throw new ArgumentNullException("operationHolder"); } // it might be possible to optimize by preventing the long to string conversion this.memoryCache.Set(key.GetHashCode().ToString(CultureInfo.InvariantCulture), operationHolder, this.cacheItemPolicy); }
protected HttpResponseMessage HandleExceptions(Exception ex, IOperationHolder <RequestTelemetry> operation, HttpRequestMessage request) { operation.Telemetry.ResponseCode = HttpStatusCode.InternalServerError.ToString(); var identifier = DateTime.Now.Ticks.ToString().Substring(8); TelClient.TrackException(ex, new Dictionary <string, string> { { "id", identifier } }); return(Request.CreateResponse(HttpStatusCode.InternalServerError, "Error ID: " + identifier)); }
public async Task Send(ConsumeContext<T> context, IPipe<ConsumeContext<T>> next) { // After the message is taken from the queue, create RequestTelemetry to track its processing. var requestTelemetry = new RequestTelemetry { Name = $"{StepName} {context.ReceiveContext.InputAddress.LocalPath} {TypeMetadataCache<T>.ShortName}" }; requestTelemetry.Context.Operation.Id = context.Headers.Get<string>(_telemetryHeaderRootKey); requestTelemetry.Context.Operation.ParentId = context.Headers.Get<string>(_telemetryHeaderParentKey); using (IOperationHolder<RequestTelemetry> operation = _telemetryClient.StartOperation(requestTelemetry)) { operation.Telemetry.Properties[MessageType] = TypeMetadataCache<T>.ShortName; if (context.MessageId.HasValue) operation.Telemetry.Properties[MessageId] = context.MessageId.Value.ToString(); if (context.ConversationId.HasValue) operation.Telemetry.Properties[ConversationId] = context.ConversationId.Value.ToString(); if (context.CorrelationId.HasValue) operation.Telemetry.Properties[CorrelationId] = context.CorrelationId.Value.ToString(); if (context.DestinationAddress != null) operation.Telemetry.Properties[DestinationAddress] = context.DestinationAddress.ToString(); if (context.ReceiveContext.InputAddress != null) operation.Telemetry.Properties[InputAddress] = context.ReceiveContext.InputAddress.ToString(); if (context.RequestId.HasValue) operation.Telemetry.Properties[RequestId] = context.RequestId.Value.ToString(); _configureOperation?.Invoke(operation, context); try { await next.Send(context).ConfigureAwait(false); operation.Telemetry.Success = true; } catch (Exception ex) { _telemetryClient.TrackException(ex, operation.Telemetry.Properties); operation.Telemetry.Success = false; throw; } finally { _telemetryClient.StopOperation(operation); } } }
protected override void FinishInternal() { if (Duration.HasValue) // should always be true by this point { _operation.Telemetry.Duration = Duration.Value; } Tracer.Client.StopOperation(_operation); _operation.Dispose(); _operation = null; }
public void Configure(IApplicationBuilder app) { if (WebHostEnvironment.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapGet("/", async context => { TelemetryClient telemetryClient = context.RequestServices.GetRequiredService <TelemetryClient>(); // You can inject TelemetryClient in controllers and services to provide additional data to app insights sdk. using (IOperationHolder <DependencyTelemetry> exportExcelOperation = telemetryClient.StartOperation <DependencyTelemetry>("ExportToExcel")) { exportExcelOperation.Telemetry.Type = "Background"; exportExcelOperation.Telemetry.Target = "ApplicationServer"; try { await Task.Delay(1000); telemetryClient.TrackTrace($"done {30}%"); await Task.Delay(1000); telemetryClient.TrackTrace($"done {60}%"); await Task.Delay(1000); telemetryClient.TrackTrace($"done {100}%"); } catch (Exception exp) { telemetryClient.TrackException(exp); throw; } finally { telemetryClient.StopOperation(exportExcelOperation); } } telemetryClient.TrackEvent("MyEvent", new Dictionary <string, string> { { "prop1", "1" }, { "prop2", "2" } }); ILogger <ClaimsIdentity> logger = context.RequestServices.GetRequiredService <ILogger <ClaimsIdentity> >(); // 3rd party libraries which relies on MS.Ext.Logging will also be captured by app insights sdk. logger.LogWarning("User {user} was logged in...", "admin"); await context.Response.WriteAsync("Hello World!"); }); }); }
/// <summary> /// Initializes a new instance of the <see cref="ApplicationInsightsOperation"/> class. /// </summary> /// <param name="provider">The Application Insights provider that created this operation.</param> /// <param name="operationName">The name of the operation.</param> /// <param name="newOperationId">The name of the newly created operation Id.</param> /// <param name="correlationContext">The correlation context.</param> /// <param name="capturedContext">The captured context to reinstate with the operation is complete.</param> public ApplicationInsightsOperation(ApplicationInsightsTelemetron provider, string operationName, string newOperationId, string correlationContext, byte[] capturedContext = null) : base(provider, operationName, newOperationId, correlationContext, capturedContext) { this.aiTelemetry = new ApplicationInsightsOperationTelemetry(operationName, newOperationId, correlationContext); this.aiTelemetry.Timestamp = DateTimeOffset.UtcNow; this.aiTelemetry.SetOperationInfo(provider); this.aiTelemetry.CorrelationContext = correlationContext; this.operationHandle = this.Provider.TelemetryClient.StartOperation(this.aiTelemetry); }
//private readonly TransactionScope transactionScope; public UnitOfWorkScope(ILifetimeScope lifetimeScope, string operationName) { this.LifetimeScope = lifetimeScope ?? throw new ArgumentNullException(nameof(lifetimeScope)); var stateManager = lifetimeScope.Resolve <IReliableStateManagerProvider>().Current; transactionProvider = lifetimeScope.Resolve <IReliableStateManagerTransactionProvider>(); ((ReliableStateManagerTransactionProvider)transactionProvider).Current = stateManager.CreateTransaction(); telemetry = lifetimeScope.Resolve <ITelemetry>(); operation = telemetry.StartOperation(operationName); //transactionScope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled); }