针对服务器端Blazor的Azure应用程序洞察? [英] Azure application insights for server-side blazor?

查看:12
本文介绍了针对服务器端Blazor的Azure应用程序洞察?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个服务器端的Blazor应用程序,我想使用Azure应用程序洞察力进行监控。目前,我只看到在启动和关闭应用程序时发送的请求,没有介于两者之间的任何内容…我找不到来自Microsoft的任何支持Blazor的文档。

可以让Azure Application Insights与服务器端Blazor完全协同工作吗?如果是这样的话,有没有人知道这方面的指南?

WASM

有两种方法可以解决这一问题--如果您计划迁移到推荐答案版本,那么基于JavaScript的方法是理想的,因为它只需要很少的更改即可转换,但是为了解决@liero所关注的问题,我在底部还包括了一种服务器端方法。

基于JavaScript的方法(Blazor WASM或服务器端)

我们在Blazor服务器端使用社区提供的BlazorApplicationInsights包来满足这一需求。是的,GitHub repo的说明与Blazor WASM的说明一致,但我很乐意为您翻译(它在服务器端也同样有效)。请注意,提供的文件路径基于Blazor服务器端模板中使用的路径。

此外,我还创建了一个Git资源库,其中包含一个项目,该项目实现了以下步骤供您审查here。您仍需要按照步骤4中指定的方式设置Application Insights检测密钥,这样才能正常工作。

  1. 将NuGet包BlazorApplicationInsights安装到Blazor服务器端项目。

  2. Startup.cs中,在ConfigureServices()方法中添加以下行:

services.AddBlazorApplicationInsights();
您可能希望增加设置以反映自定义角色和实例值。您可以使用以下内容来处理此(相同位置):

services.AddBlazorApplicationInsights(async appInsights => {
  var telemetryItem = new TelemetryItem 
  {
    Tags = new Dictionary<string, object> 
    {
      {"ai.cloud.role", "SPA"},
      {"ai.cloud.roleInstance", "Blazor server-side"}
    }
  };

  await appInsights.AddTelemetryInitializer(telemetryItem);
});
  1. 将以下@Using语句添加到_Imports.razor
@using BlazorApplicationInsights
  1. 将对Application Insights JS文件的引用添加到Pages/_Host.cshtml文件的头部。已从here中拉出脚本。请注意接近末尾的一行,您需要在该行中将字符串值替换为Application Insights检测密钥。
<head>
  <!-- ... -->
<script type="text/javascript">
        !function (T, l, y) { var S = T.location, k = "script", D = "instrumentationKey", C = "ingestionendpoint", I = "disableExceptionTracking", E = "ai.device.", b = "toLowerCase", w = "crossOrigin", N = "POST", e = "appInsightsSDK", t = y.name || "appInsights"; (y.name || T[e]) && (T[e] = t); var n = T[t] || function (d) { var g = !1, f = !1, m = { initialize: !0, queue: [], sv: "5", version: 2, config: d }; function v(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_" + (m.sv || m.version), { time: function () { var e = new Date; function t(e) { var t = "" + e; return 1 === t.length && (t = "0" + t), t } return e.getUTCFullYear() + "-" + t(1 + e.getUTCMonth()) + "-" + t(e.getUTCDate()) + "T" + t(e.getUTCHours()) + ":" + t(e.getUTCMinutes()) + ":" + t(e.getUTCSeconds()) + "." + ((e.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 } } } } var h = d.url || y.src; if (h) { function a(e) { var t, n, a, i, r, o, s, c, u, p, l; g = !0, m.queue = [], f || (f = !0, t = h, s = function () { var e = {}, t = d.connectionString; if (t) for (var n = t.split(";"), a = 0; a < n.length; a++) { var i = n[a].split("="); 2 === i.length && (e[i[0][b]()] = i[1]) } if (!e[C]) { var r = e.endpointsuffix, o = r ? e.location : null; e[C] = "https://" + (o ? o + "." : "") + "dc." + (r || "services.visualstudio.com") } return e }(), c = s[D] || d[D] || "", u = s[C], p = u ? u + "/v2/track" : d.endpointUrl, (l = []).push((n = "SDK LOAD Failure: Failed to load Application Insights SDK script (See stack for details)", a = t, i = p, (o = (r = v(c, "Exception")).data).baseType = "ExceptionData", o.baseData.exceptions = [{ typeName: "SDKLoadFailed", message: n.replace(/./g, "-"), hasFullStack: !1, stack: n + "
Snippet failed to load [" + a + "] -- Telemetry is disabled
Help Link: https://go.microsoft.com/fwlink/?linkid=2128109
Host: " + (S && S.pathname || "_unknown_") + "
Endpoint: " + i, parsedStack: [] }], r)), l.push(function (e, t, n, a) { var i = v(c, "Message"), r = i.data; r.baseType = "MessageData"; var o = r.baseData; return o.message = 'AI (Internal): 99 message:"' + ("SDK LOAD Failure: Failed to load Application Insights SDK script (See stack for details) (" + n + ")").replace(/"/g, "") + '"', o.properties = { endpoint: a }, i }(0, 0, t, p)), function (e, t) { if (JSON) { var n = T.fetch; if (n && !y.useXhr) n(t, { method: N, body: JSON.stringify(e), mode: "cors" }); else if (XMLHttpRequest) { var a = new XMLHttpRequest; a.open(N, t), a.setRequestHeader("Content-type", "application/json"), a.send(JSON.stringify(e)) } } }(l, p)) } function i(e, t) { f || setTimeout(function () { !t && m.core || a() }, 500) } var e = function () { var n = l.createElement(k); n.src = h; var e = y[w]; return !e && "" !== e || "undefined" == n[w] || (n[w] = e), n.onload = i, n.onerror = a, n.onreadystatechange = function (e, t) { "loaded" !== n.readyState && "complete" !== n.readyState || i(0, t) }, n }(); y.ld < 0 ? l.getElementsByTagName("head")[0].appendChild(e) : setTimeout(function () { l.getElementsByTagName(k)[0].parentNode.appendChild(e) }, y.ld || 0) } try { m.cookie = l.cookie } catch (p) { } function t(e) { for (; e.length;)!function (t) { m[t] = function () { var e = arguments; g || m.queue.push(function () { m[t].apply(m, e) }) } }(e.pop()) } var n = "track", r = "TrackPage", o = "TrackEvent"; t([n + "Event", n + "PageView", n + "Exception", n + "Trace", n + "DependencyData", n + "Metric", n + "PageViewPerformance", "start" + r, "stop" + r, "start" + o, "stop" + o, "addTelemetryInitializer", "setAuthenticatedUserContext", "clearAuthenticatedUserContext", "flush"]), m.SeverityLevel = { Verbose: 0, Information: 1, Warning: 2, Error: 3, Critical: 4 }; var s = (d.extensionConfig || {}).ApplicationInsightsAnalytics || {}; if (!0 !== d[I] && !0 !== s[I]) { var c = "onerror"; t(["_" + c]); var u = T[c]; T[c] = function (e, t, n, a, i) { var r = u && u(e, t, n, a, i); return !0 !== r && m["_" + c]({ message: e, url: t, lineNumber: n, columnNumber: a, error: i }), r }, d.autoExceptionInstrumented = !0 } return m }(y.cfg); function a() { y.onInit && y.onInit(n) } (T[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", // The SDK URL Source
            // name: "appInsights", // Global SDK Instance name defaults to "appInsights" when not supplied
            // ld: 0, // Defines the load delay (in ms) before attempting to load the sdk. -1 = block page load and add to head. (default) = 0ms load after timeout,
            // useXhr: 1, // Use XHR instead of fetch to report failures (if available),
            crossOrigin: "anonymous", // When supplied this will add the provided value as the cross origin attribute on the script tag
            // onInit: null, // Once the application insights instance has loaded and initialized this callback function will be called with 1 argument -- the sdk instance (DO NOT ADD anything to the sdk.queue -- As they won't get called)
            cfg: { // Application Insights Configuration
                instrumentationKey: "INSTRUMENTATION_KEY"
            }
        });
    </script>
</head>
  1. </body>结束标记之前将JS互操作添加到Pages/_Host.cshtml文件的底部:
<body>
  <!-- ... ->
  <script src="_content/BlazorApplicationInsights/JsInterop.js"></script>
</body>
  1. 将以下内容添加到App.razor文件的顶部以支持自动导航跟踪:
<ApplicationInsightsComponent />
  1. 此库将在路线更改时自动触发";Track Page View";,但其他任何操作都需要您手动触发事件。下面是您的一个页面中可能有的示例(请参阅更多示例方法here):
@page "/"
@inject IApplicationInsights AppInsights

<button class="btn btn-primary" @onclick="TrackEvent">Track Event</button>
<button class="btn btn-secondary" @onclick="TrackMetric">Track Metric</button>

@code {
  private async Task TrackEvent()
  {
    await AppInsights.TrackEvent("My Event");
  }

  private async Task TrackMetric()
  {
    await AppInsights.TrackMetric("myMetric", 100, 200, 1, 200, new Dictionary<string,object> {{"customProperty", "customValue"}});
    await AppInsights.Flush();
  }
}

您将注意到在sample code中使用PageViewPerformanceTelemtry支持TrackPageViewPerformance。您可能希望在@代码挡路中调用它,而不是绑定到按钮,如下所示:

protected override async Task OnAfterRenderAsync(bool firstRender)
{
    await AppInsights.TrackPageViewPerformance(new PageViewPerformanceTelemetry());
}

Application Insight SDK方法(Blazor服务器端)

  1. 将NuGet包Microsoft.ApplicationInsights.AspNetCore安装到Blazor服务器端项目。

  2. ConfigureServices()方法的Startup.cs中,添加以下行,将字符串参数替换为您的App Insights检测密钥:

services.AddBlazorApplicationInsights("INSERT YOUR INSTRUMENTATION KEY HERE");

或者,您也可以消除字符串并将密钥存储在以下任一环境变量中:

  • APPINSIGHTS_INSTRUMENTIONKEY
  • ApplicationInsights:InstrumentationKey

您可以找到其他文档here,其中介绍了各种选项,您也可以在此处传入有关您可能要启用的其他遥测模块的信息。

  1. 将以下@using语句添加到_Imports.razor
@using Microsoft.ApplicationInsights
  1. 因为Application Insights没有与Blazor进行任何本机集成,所以您需要自己挂接您想要跟踪的所有内容。我们将在本节的其余部分介绍实现此目的的一些方法。

首先,我们需要创建主机组件来跟踪各种导航操作。在您的共享目录中创建一个名为ApplicationInsightsComponent.cs的新CS文件,并填充以下内容:

using System;
using Microsoft.ApplicationInsights;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Routing;

namespace ApplicationInsightsServerSample.Shared
{
    public class ApplicationInsightsComponent : ComponentBase, IDisposable
    {
        [Inject]
        private TelemetryClient _telemetryClient { get; init; }

        [Inject]
        private NavigationManager _navigationManager { get; init; }

        protected override void OnAfterRender(bool firstRender)
        {
            if (firstRender)
            {
                _navigationManager.LocationChanged += NavigationManagerOnLocationChanged;
            }
        }

        private void NavigationManagerOnLocationChanged(object? sender, LocationChangedEventArgs e)
        {
            _telemetryClient.TrackPageView(e.Location); //Set the argument to whatever you'd like to name the page
            
        }


        public void Dispose()
        {
            _navigationManager.LocationChanged -= NavigationManagerOnLocationChanged;
        }
    }
}

App.razor文件中,将以下内容添加到顶部:

<ApplicationInsightsComponent />

让我们还实现一些东西来捕获应用程序中抛出的任何异常。创建 共享目录中名为Error.razor的另一个文件,并填充以下内容:

@inject TelemetryClient _telemetryClient

<CascadingValue Value=this>
    @ChildContent
</CascadingValue>

@code 
{
    [Parameter]
    public RenderFragment ChildContent { get; set; }

    public void ProcessError(Exception ex)
    {
        _telemetryClient.TrackException(ex);
    }
}

返回到App.razor文件,使用如下所示的新组件包装路由器:

<Error>
  <Router ...>
    ...
  </Router>
</Error>

然后在任何组件中,使用以下内容将错误组件指定为代码挡路中的级联参数:

@code {
  [CascadingParameter]
  public Error Error {get; set;}
}

当您以其他方式使用Try/Catch挡路包装操作时,请在Catch内调用Error.ProcessError(ex)以将异常向上传播到我们的错误组件:

try 
{
  // ...
}
catch (Exception ex)
{
  Error.ProcessError(ex);
}

除此之外,您无疑希望跟踪各个页面上的任意数量的事件,因此我将以一个TrackEvent示例来结束。就像在另一个答案中一样,让我们使用按钮重新调整页面示例的用途,并在这里重新处理它以实现兼容性:

@page "/"
@inject TelemetryClient _telemetryClient

<button class="btn btn-primary" @onclick="TrackEvent">Track Event</button>
<button class="btn btn-secondary" @onclick="TrackMetric">Track Metric</button>

@code {
  private void TrackEvent()
  {
    await _telemetryClient.TrackEvent("My Event");
  }

  private void TrackMetric()
  {
    _telemetryClient.TrackMetric("myMetric", 100, new Dictionary<string,string> {{"customProperty", "customValue"}});
  }
}

我希望这对您有所帮助,但我很乐意为您提供您需要的任何其他详细信息来更新此答案!

这篇关于针对服务器端Blazor的Azure应用程序洞察?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆