javascript - Application Insight 中的 JS 异常

标签 javascript azure .net-6.0 azure-application-insights

我有一个 .net 6 Web 应用程序,我正在尝试查找如何在控制台中显示 JS 异常以登录应用程序洞察。

我试图找出答案,但很难找到任何可以帮助的东西。

我已经成功地发送了在 AI 中捕获的 nlog、sql,但无法对 JS 异常完成相同的操作。

如果需要我提供任何其他详细信息,请告诉我。

CSProj

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>

  <ItemGroup>
    <Content Remove="bundleconfig.json" />
  </ItemGroup>

  <ItemGroup>
    <None Include="bundleconfig.json" />
  </ItemGroup>

  <ItemGroup>
    <PackageReference Include="BuildBundlerMinifier" Version="3.2.449" />   
    <PackageReference Include="Hangfire.AspNetCore" Version="1.7.34" />
    <PackageReference Include="Hangfire.SqlServer" Version="1.7.34" />
    <PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.21.0" />
    <PackageReference Include="Microsoft.ApplicationInsights.NLogTarget" Version="2.21.0" />
    <PackageReference Include="Microsoft.AspNet.WebApi.Client" Version="5.2.9" />
    <PackageReference Include="Microsoft.AspNetCore" Version="2.2.0" />
    <PackageReference Include="Microsoft.AspNetCore.Authentication.Negotiate" Version="6.0.16" />
    <PackageReference Include="Microsoft.AspNetCore.Hosting" Version="2.2.7" />
    <PackageReference Include="Microsoft.AspNetCore.Html.Abstractions" Version="2.2.0" />
    <PackageReference Include="Microsoft.AspNetCore.Http" Version="2.2.2" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc.Core" Version="2.2.5" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="6.0.16" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc.ViewFeatures" Version="2.2.0" />
    <PackageReference Include="Microsoft.Data.SqlClient" Version="5.1.1" />
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.5" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="7.0.5">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="7.0.5" />
    <PackageReference Include="Microsoft.Extensions.Azure" Version="1.6.3" />
    <PackageReference Include="Microsoft.Identity.Abstractions" Version="3.1.0" />
    <PackageReference Include="Microsoft.Identity.Web" Version="2.7.0" />
    <PackageReference Include="Microsoft.Identity.Web.DownstreamApi" Version="2.9.0" />
    <PackageReference Include="Microsoft.Identity.Web.UI" Version="2.7.0" />
    <PackageReference Include="NLog" Version="5.2.0" />
    <PackageReference Include="NLog.Web.AspNetCore" Version="5.3.0" />
    <PackageReference Include="Telerik.UI.for.AspNet.Core" Version="2022.3.1109" />
    <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.16" />
  </ItemGroup>
  <ItemGroup>
      <Compile Include="" />
  </ItemGroup>
  <ItemGroup>
    <ProjectReference Include="" />
    <ProjectReference Include="" />
  </ItemGroup>

  <ItemGroup>
    <Folder Include="Content\kendo\2022\" />
    <Folder Include="Scripts\Bootstrap\" />
    <Folder Include="Scripts\kendo\2022\" />
    <Folder Include="wwwroot\lib\pages\" />
  </ItemGroup>

</Project>

设置

services.AddApplicationInsightsTelemetry();
        services.ConfigureTelemetryModule<DependencyTrackingTelemetryModule>((module, o) => module.EnableSqlCommandTextInstrumentation = true);

在正常的 AI 设置之后,我仍然在控制台中看到一个错误 enter image description here

最佳答案

要在Application Insights中跟踪JS异常, 在 Layout.cshtml 的 head 标签中添加以下 JS。

我引用了这个MSDoc并添加了 JS。

  • 添加 ConnectionString 或 Instrumentationkey。
<script type="text/javascript">
   !function (v, y, T) { var S = v.location, k = "script", D = "instrumentationKey", C = "ingestionendpoint", I = "disableExceptionTracking", E = "ai.device.", b = "toLowerCase", w = (D[b](), "crossOrigin"), N = "POST", e = "appInsightsSDK", t = T.name || "appInsights", n = ((T.name || v[e]) && (v[e] = t), v[t] || function (l) { var u = !1, d = !1, g = { initialize: !0, queue: [], sv: "6", version: 2, config: l }; function m(e, t) { var n = {}, a = "Browser"; return n[E + "id"] = a[b](), n[E + "type"] = a, n["ai.operation.name"] = S && S.pathname || "_unknown_", n["ai.internal.sdkVersion"] = "javascript:snippet_" + (g.sv || g.version), { time: (a = new Date).getUTCFullYear() + "-" + i(1 + a.getUTCMonth()) + "-" + i(a.getUTCDate()) + "T" + i(a.getUTCHours()) + ":" + i(a.getUTCMinutes()) + ":" + i(a.getUTCSeconds()) + "." + (a.getUTCMilliseconds() / 1e3).toFixed(3).slice(2, 5) + "Z", iKey: e, name: "Microsoft.ApplicationInsights." + e.replace(/-/g, "") + "." + t, sampleRate: 100, tags: n, data: { baseData: { ver: 2 } } }; function i(e) { e = "" + e; return 1 === e.length ? "0" + e : e } } var e, n, f = l.url || T.src; function a(e) { var t, n, a, i, o, s, r, c, p; u = !0, g.queue = [], d || (d = !0, i = f, r = (c = function () { var e, t = {}, n = l.connectionString; if (n) for (var a = n.split(";"), i = 0; i < a.length; i++) { var o = a[i].split("="); 2 === o.length && (t[o[0][b]()] = o[1]) } return t[C] || (t[C] = "https://" + ((e = (n = t.endpointsuffix) ? t.location : null) ? e + "." : "") + "dc." + (n || "services.visualstudio.com")), t }()).instrumentationkey || l[D] || "", c = (c = c[C]) ? c + "/v2/track" : l.endpointUrl, (p = []).push((t = "SDK LOAD Failure: Failed to load Application Insights SDK script (See stack for details)", n = i, o = c, (s = (a = m(r, "Exception")).data).baseType = "ExceptionData", s.baseData.exceptions = [{ typeName: "SDKLoadFailed", message: t.replace(/\./g, "-"), hasFullStack: !1, stack: t + "\nSnippet failed to load [" + n + "] -- Telemetry is disabled\nHelp Link: https://go.microsoft.com/fwlink/?linkid=2128109\nHost: " + (S && S.pathname || "_unknown_") + "\nEndpoint: " + o, parsedStack: [] }], a)), p.push((s = i, t = c, (o = (n = m(r, "Message")).data).baseType = "MessageData", (a = o.baseData).message = 'AI (Internal): 99 message:"' + ("SDK LOAD Failure: Failed to load Application Insights SDK script (See stack for details) (" + s + ")").replace(/\"/g, "") + '"', a.properties = { endpoint: t }, n)), i = p, r = c, JSON && ((o = v.fetch) && !T.useXhr ? o(r, { method: N, body: JSON.stringify(i), mode: "cors" }) : XMLHttpRequest && ((s = new XMLHttpRequest).open(N, r), s.setRequestHeader("Content-type", "application/json"), s.send(JSON.stringify(i))))) } function i(e, t) { d || setTimeout(function () { !t && g.core || a() }, 500) } f && ((n = y.createElement(k)).src = f, !(o = T[w]) && "" !== o || "undefined" == n[w] || (n[w] = o), n.onload = i, n.onerror = a, n.onreadystatechange = function (e, t) { "loaded" !== n.readyState && "complete" !== n.readyState || i(0, t) }, e = n, T.ld < 0 ? y.getElementsByTagName("head")[0].appendChild(e) : setTimeout(function () { y.getElementsByTagName(k)[0].parentNode.appendChild(e) }, T.ld || 0)); try { g.cookie = y.cookie } catch (h) { } function t(e) { for (; e.length;)!function (t) { g[t] = function () { var e = arguments; u || g.queue.push(function () { g[t].apply(g, e) }) } }(e.pop()) } var s, r, o = "track", c = "TrackPage", p = "TrackEvent", o = (t([o + "Event", o + "PageView", o + "Exception", o + "Trace", o + "DependencyData", o + "Metric", o + "PageViewPerformance", "start" + c, "stop" + c, "start" + p, "stop" + p, "addTelemetryInitializer", "setAuthenticatedUserContext", "clearAuthenticatedUserContext", "flush"]), g.SeverityLevel = { Verbose: 0, Information: 1, Warning: 2, Error: 3, Critical: 4 }, (l.extensionConfig || {}).ApplicationInsightsAnalytics || {}); return !0 !== l[I] && !0 !== o[I] && (t(["_" + (s = "onerror")]), r = v[s], v[s] = function (e, t, n, a, i) { var o = r && r(e, t, n, a, i); return !0 !== o && g["_" + s]({ message: e, url: t, lineNumber: n, columnNumber: a, error: i, evt: v.event }), o }, l.autoExceptionInstrumented = !0), g }(T.cfg)); function a() { T.onInit && T.onInit(n) } (v[t] = n).queue && 0 === n.queue.length ? (n.queue.push(a), n.trackPageView({})) : a() }(window, document, {
       src: "https://js.monitor.azure.com/scripts/b/ai.2.min.js",

       crossOrigin: "anonymous",

       cfg: {
           connectionString: "InstrumentationKey=******;IngestionEndpoint=https://******.in.applicationinsights.azure.com/;LiveEndpoint=https://******.livediagnostics.monitor.azure.com/"
       }

   });

   window.appInsights = appInsights;
   appInsights.trackPageView();
   try {
       throw new Error("Logging Exception from Javascript");
   } catch (error) {
       appInsights.trackException("Logging Exception from Javascript.");
       appInsights.trackException({ error });
   }
</script>
appInsights.trackPageView();//For Logging Page Views
appInsights.trackException();//For Logging JS Exception

输出:

enter image description here

"Failed to initialize AppInsights JS SDK: Cannot load Application Insights SDK,

  • 我已经安装了与您提供的相同的软件包和版本 (.csproj)。
  • 我发现这些版本已被弃用。

enter image description here

将所有软件包更新到最新版本。

关于javascript - Application Insight 中的 JS 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76573055/

相关文章:

javascript - 在 Edge 浏览器中加载 GWT 页面/项目比 Chrome 和 Safari 浏览器花费更多时间

azure - 无法调试 Azure webjobs - webjob 进程未显示在 "Attach to process"对话框中

c# - Azure 分析服务的 RESTful API 不起作用

c# - Asp.Net 核心 6 session key

uwp - 如何在桌面应用程序中实现WinUI3中的亚克力窗效果?

javascript - HTML本地存储多个键?

javascript - Angularjs:数组分配问题

javascript - 复选框标签的放置

angular - 通过 Azure 广告对 Angular 中的用户进行身份验证并授权 Blob 存储