javascript - 使用 Application Insights 配置 NLog 和 JS 异常

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

我已经设置了 NLog 来与 Applicatin Insights 配合使用,还记录 js 异常,并且正在按要求工作。但是,我正在努力使仪器 key 动态化,以便它针对特定于环境的应用程序洞察实例。

NLog 配置目标

<target name="aiTarget" xsi:type="ApplicationInsightsTarget"
     layout="${longdate}|${event-properties:item=EventId_Id:whenEmpty=0}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}">
      <instrumentationKey>"mydevappinsightinstrumentationkey"</instrumentationKey>
      <contextproperty name="threadid" layout="${threadid}" />
    </target>

针对 JS 异常的布局 cshtm

<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=mydevappinsightinstrumentationkey;IngestionEndpoint=mydevappinsightingestionendpoint"
            }

        });

        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>

如何在上述场景中使检测 key 动态化?

最佳答案

检测 key 可以设置为动态,以便它针对特定于环境的应用程序洞察实例,如下所示。

const config = require('config');
const appInsights = require('applicationinsights');

// Determine the environment (development, production, etc.)
const environment = process.env.NODE_ENV || 'development';

// Get the instrumentation key from the configuration based on the environment
const instrumentationKey = config.get('appInsightsInstrumentationKey');

// Initialize Application Insights with the dynamic instrumentation key
appInsights
  .setup(instrumentationKey)
  .start();

  • 安装npm install applicationinsights config mkdir配置
  • 在项目中创建一个 config 目录来存储特定于环境的配置文件。

mkdir 配置

配置应用程序洞察

在 Azure 门户中,创建一个 Application Insights 资源(如果尚未创建)。您将需要此资源的检测 key 。

创建配置文件

config 目录中,创建两个配置文件:development.jsondevelopment.json。将 “YOUR_DEVELOPMENT_INSTRUMENTATION_KEY”“YOUR_PRODUCTION_INSTRUMENTATION_KEY” 替换为您的实际检测 key 。

development.json

{

"appInsightsInstrumentationKey_development":  "key "

}
  • 在 bash 中运行 set NODE_ENV=development 并运行代码。

在 JS 布局 cshtm 中:

@{
    string instrumentationKey = Environment.GetEnvironmentVariable("APPINSIGHTS_INSTRUMENTATIONKEY");
}

<script type="text/javascript">
    !function (v, y, T) {
    
            };

            // Rest of your script here...

            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=" + @instrumentationKey + ";IngestionEndpoint=mydevappinsightingestionendpoint"
            }
        });

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

enter image description here

关于javascript - 使用 Application Insights 配置 NLog 和 JS 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77094034/

相关文章:

javascript - jQuery 跨域 POST 恶作剧

javascript - 渲染性能 - 图像与 css 渐变或带边框的框阴影?

javascript - 使用纯js将具有子级和孙级子级的整个元素附加到另一个元素

asp.net - 将azure db添加到mvc5项目

azure - 如果 Azure 部署插槽已关闭,您是否仍需为其运行的计算机付费?

c# - .Net 6 - 自定义中间件日志记录 - 混合响应和请求

c# - 是否可以使用 .NET 6 中的 .NET 4.8 库?

javascript - 使用 NodeJS 实现自动化

c# - DynamicTableEntity 类有何相关性?

c# - VB.NET 与 C# 在控制台应用程序结束后没有显式释放任何内容而退出 Excel 有何不同?