Angular SPA中如何通过Application Insights追踪App Service服务信息
Angular SPA 结合 Application Insights 追踪 App Service 方案
1. 在 PageView 事件中添加 App Service 名称追踪
你可以通过全局默认属性或手动追踪时自定义属性两种方式,把App Service名称附加到PageView事件中:
方式一:全局初始化时配置默认属性
在Application Insights初始化阶段,通过defaultProperties全局注入App Service名称(建议从Angular环境变量读取,便于多环境部署切换):
import { ApplicationInsights } from '@microsoft/applicationinsights-web'; import { AngularPlugin } from '@microsoft/applicationinsights-angularplugin-js'; import { environment } from '../environments/environment'; const angularPlugin = new AngularPlugin(); const appInsights = new ApplicationInsights({ config: { instrumentationKey: '你的InstrumentationKey', // 全局默认属性,所有PageView都会带上这个字段 defaultProperties: { appServiceName: environment.appServiceName } }, extensions: [angularPlugin], extensionConfig: { [angularPlugin.identifier]: { router: this.router } // 传入Angular路由实例 } }); appInsights.loadAppInsights();
方式二:手动触发PageView时添加属性
如果需要针对特定页面单独设置,可在组件中调用trackPageView时传入自定义属性:
// 在组件或服务中注入ApplicationInsights实例 constructor(private appInsights: ApplicationInsights) {} // 手动追踪页面时附加属性 trackCustomPage() { this.appInsights.trackPageView({ name: '用户详情页', properties: { appServiceName: environment.appServiceName } }); }
2. 在请求日志中追踪处理请求的App Service服务
针对前端发起的API请求,可通过遥测初始化器或HTTP拦截器两种方式,给请求日志添加处理该请求的App Service标识:
方式一:通过遥测初始化器全局注入
利用addTelemetryInitializer给所有依赖(请求)日志统一添加属性,适合已知API所属App Service的场景:
// 初始化Application Insights后添加初始化器 appInsights.addTelemetryInitializer((item) => { // 只针对依赖类型的日志(即API请求)添加属性 if (item.type === 'dependency') { item.properties = { ...item.properties, processingAppServiceName: environment.apiAppServiceName }; } return true; });
方式二:从后端响应头获取并记录
如果后端部署在App Service,可让后端将自身服务名称(通过App Service环境变量WEBSITE_SITE_NAME获取)添加到响应头(比如X-App-Service-Name),前端通过HTTP拦截器读取后附加到日志:
后端示例(以ASP.NET Core为例)
// 在Startup.cs/Program.cs中添加响应头 app.Use(async (context, next) => { context.Response.Headers.Append("X-App-Service-Name", Environment.GetEnvironmentVariable("WEBSITE_SITE_NAME")); await next(); });
前端HTTP拦截器实现
import { Injectable } from '@angular/core'; import { HttpInterceptor, HttpRequest, HttpHandler, HttpResponse } from '@angular/common/http'; import { tap } from 'rxjs/operators'; import { ApplicationInsights } from '@microsoft/applicationinsights-web'; @Injectable() export class AppServiceTrackingInterceptor implements HttpInterceptor { constructor(private appInsights: ApplicationInsights) {} intercept(request: HttpRequest<any>, next: HttpHandler) { const startTime = Date.now(); return next.handle(request).pipe( tap(event => { if (event instanceof HttpResponse) { const appServiceName = event.headers.get('X-App-Service-Name'); if (appServiceName) { // 更新当前请求的日志属性 this.appInsights.trackDependency({ name: request.url, data: request.method, duration: Date.now() - startTime, success: event.ok, properties: { processingAppServiceName: appServiceName } }); } } }) ); } }
注意:记得在Angular的
providers中注册这个拦截器。
内容的提问来源于stack exchange,提问作者lightbulb05
相关产品推荐
相关产品推荐

