javascript - 使用 Javascript 中的 App Insights TrackEvent 将自定义复杂属性发送到遥测到 Azure 门户?

标签 javascript azure azure-application-insights azure-log-analytics azure-analytics

如何使用基本 Javascript(而非 NodeJS)中的 App Insights TrackEvent 将自定义复杂非字符串属性发送到遥测到 Azure 门户?

我通过以下设置片段初始化了 Application Insights JavaScript SDK:

<script type='text/javascript'>
        var appInsights=window.appInsights||function(config)
        {
            function r(config){ t[config] = function(){ var i = arguments; t.queue.push(function(){ t[config].apply(t, i)})} }
            var t = { config:config},u=document,e=window,o='script',s=u.createElement(o),i,f;for(s.src=config.url||'//az416426.vo.msecnd.net/scripts/a/ai.0.js',u.getElementsByTagName(o)[0].parentNode.appendChild(s),t.cookie=u.cookie,t.queue=[],i=['Event','Exception','Metric','PageView','Trace','Ajax'];i.length;)r('track'+i.pop());return r('setAuthenticatedUserContext'),r('clearAuthenticatedUserContext'),config.disableExceptionTracking||(i='onerror',r('_'+i),f=e[i],e[i]=function(config, r, u, e, o) { var s = f && f(config, r, u, e, o); return s !== !0 && t['_' + i](config, r, u, e, o),s}),t
        }({
            instrumentationKey: "@Microsoft.ApplicationInsights.Extensibility.TelemetryConfiguration.Active.InstrumentationKey"
        });
        window.appInsights=appInsights;
        appInsights.trackPageView();
    </script>

我尝试了这里的示例 https://github.com/microsoft/ApplicationInsights-JS在这里 https://learn.microsoft.com/en-us/azure/azure-monitor/app/api-custom-events-metrics#properties但没有成功:

appInsights.trackEvent({
  name: 'EventName',
  properties: { // accepts any type
    prop1: 'string',
    prop2: 123.45,
    prop3: { 
        nested: 'objects are okay too'
    }
  }
});

在发送到 Azure 的 Ajax 跟踪请求中,发送的负载具有以下形式:

ver: 2
name:
   name: 'EventName'
      properties:
         prop1: 'string'
         prop2: 123.45
         prop3:
            nested: 'objects are okay too'

在 Azure Portal App Insights 中,我得到以下信息:

CUSTOM EVENT
Event name  [object Object]

我还在控制台中收到 Javascript 警告:

Logging.ts:206 AI: CannotSerializeObjectNonSerializable 
message:"Attempting to serialize an object which does not implement ISerializable" 
props:"{name:name}"

我只能通过单独指定 name 属性、字符串类型属性和一级嵌套属性来发送。

测试成功:

appInsights.trackEvent("EventName1", { properties: 'something' });
appInsights.trackEvent("EventName2", { prop1: 'something', prop2: 'prop2' });

不成功的测试:

appInsights.trackEvent("EventName3", { prop1: 'prop1', nestedProp2: {prop2: 'prop2'} });
appInsights.trackEvent('EventName4', { properties: { dataToSend: 'something' }, measurements: {prop1: 'prop1', prop2: 'prop2'}});

最佳答案

问题出在 SDK 版本上。

在Azure门户和浏览器AJAX调用的tags属性中,它显示我正在使用1.0.21 SDK版本,这些示例适用于2.5.3 SDK版本,这些版本并不落后兼容。

解决方案是通过替换代码段设置来升级到最新的 SDK 版本(主要区别在于更改 url az416426.vo.msecnd.net/scripts/a/ai.0.js 就这个 az416426.vo.msecnd.net/scripts/b/ai.2.min.js)。

新的代码片段设置:

<script type="text/javascript">
var sdkInstance="appInsightsSDK";window[sdkInstance]="appInsights";var aiName=window[sdkInstance],aisdk=window[aiName]||function(n){var o={config:n,initialize:!0},t=document,e=window,i="script";setTimeout(function(){var e=t.createElement(i);e.src=n.url||"https://az416426.vo.msecnd.net/scripts/b/ai.2.min.js",t.getElementsByTagName(i)[0].parentNode.appendChild(e)});try{o.cookie=t.cookie}catch(e){}function a(n){o[n]=function(){var e=arguments;o.queue.push(function(){o[n].apply(o,e)})}}o.queue=[],o.version=2;for(var s=["Event","PageView","Exception","Trace","DependencyData","Metric","PageViewPerformance"];s.length;)a("track"+s.pop());var r="Track",c=r+"Page";a("start"+c),a("stop"+c);var u=r+"Event";if(a("start"+u),a("stop"+u),a("addTelemetryInitializer"),a("setAuthenticatedUserContext"),a("clearAuthenticatedUserContext"),a("flush"),o.SeverityLevel={Verbose:0,Information:1,Warning:2,Error:3,Critical:4},!(!0===n.disableExceptionTracking||n.extensionConfig&&n.extensionConfig.ApplicationInsightsAnalytics&&!0===n.extensionConfig.ApplicationInsightsAnalytics.disableExceptionTracking)){a("_"+(s="onerror"));var p=e[s];e[s]=function(e,n,t,i,a){var r=p&&p(e,n,t,i,a);return!0!==r&&o["_"+s]({message:e,url:n,lineNumber:t,columnNumber:i,error:a}),r},n.autoExceptionInstrumented=!0}return o}(
{
  instrumentationKey:"INSTRUMENTATION_KEY"
}
);(window[aiName]=aisdk).queue&&0===aisdk.queue.length&&aisdk.trackPageView({});
</script>

现在,以下自定义事件按预期在 Azure 门户 App Insights 中发送和接收:

appInsights.trackEvent({
  name: 'EventName',
  properties: { // accepts any type
    prop1: 'string',
    prop2: 123.45,
    prop3: { 
        nested: 'objects are okay too'
    }
  }
});

关于javascript - 使用 Javascript 中的 App Insights TrackEvent 将自定义复杂属性发送到遥测到 Azure 门户?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60959882/

相关文章:

wcf - Windows 8 上使用 Microsoft 帐户的 Azure ACS 2.0

azure - logger.Log 语句在 Azure 门户中的什么位置?

javascript - zipAll 函数(例如 lodash/fp)的流类型是什么?

javascript - 跟踪像素的动态响应?

Javascript,用数组过滤数组

azure - Azure Functions 何时支持 AD MSAL 3.0 身份验证?

php - javascript无法从HTML输入标签分配隐藏的输入元素

.net - 如何获取Azure环境名称

azure - 使用 Azure Application Insights 创建有关调用第三方 API 的警报

.net-core - 将应用洞察跟踪日志记录添加到 .net 核心控制台应用程序