Отправить пользовательские сложные свойства в Telemetry на Azure Portal с App Insights TrackEvent в Javascript? - PullRequest
0 голосов
/ 01 апреля 2020

Как я могу отправить пользовательские сложные нестроковые свойства в Телеметрию на Azure Портал с App Insights TrackEvent в основном c Javascript (не NodeJS)?

Я инициализировал 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://docs.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'
    }
  }
});

В запросе отслеживания Ajax, отправленном на Azure, отправленная полезная нагрузка имеет следующую форму:

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

А в Azure Insight Appal App я получаю следующее:

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'}});

1 Ответ

1 голос
/ 09 апреля 2020

Проблема связана с версией SDK.

На портале Azure и в свойстве tags из браузера AJAX вызывает его, показывает, что я использую версию SDK 1.0.21, и те, примеры для версии 2.5.3 SDK, которые не имеют обратной совместимости.

Решение было обновить до последней версии SDK, заменив настройку сниппета (основное отличие было бы в изменении URL az416426.vo.msecnd.net/scripts/a/ai.0.js этим one 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>

Теперь следующее событие Cutom отправляется и принимается в Azure портала App Insights, как и ожидалось:

appInsights.trackEvent({
  name: 'EventName',
  properties: { // accepts any type
    prop1: 'string',
    prop2: 123.45,
    prop3: { 
        nested: 'objects are okay too'
    }
  }
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...