asp.net - System.Diagnostics.TraceSource 未将数据发送到 Application Insights

标签 asp.net azure wcf azure-application-insights trace

我在我的项目中设置了应用程序洞察,工作正常,它将数据发送到 Azure,没有任何问题,现在我尝试使用已实现的 System.Diagnostics.SourceTrace 将一些跟踪日志发送到发送到 azure 的遥测数据在 Webhost 应用程序中引用的内部 nuget 包中(此 nuget 包不包含对应用程序见解的引用),问题是......出于某种原因,它只是没有到达该代码,嗯,它确实到达了并且它不同时,当我在输出窗口中调试时,我可以看到当它命中 Sytem.Diagnostics.TraceEvent() 方法时创建了一个事件,但它显示如下

Application Insights Telemetry (unconfigured): {"name":"Microsoft.ApplicationInsights.Message","time":"2021-09-01T22:43:18.7652108Z","tags":{"ai.cloud.roleInstance":

这让我认为,由于某种原因,遥测客户端正在丢失对仪器 key 或类似内容的引用,而且我不知道如何解决这个问题,因为它只发生在那里。

编辑: 以下是我们如何设置跟踪源,此代码位于 webhost 应用程序的 web.config 文件中,该文件引用另一个项目,该项目引用发生日志记录的 nuget 包。

        <source name="MySource" switchValue="Error, Information, Warning">
          <listeners>
            <add name="AppInsights"  type="Microsoft.ApplicationInsights.TraceListener.ApplicationInsightsTraceListener, Microsoft.ApplicationInsights.TraceListener" />
          </listeners>
        </source>

我调试了发生日志记录的类,当我评估遥测配置对象时,它缺少仪器 key (这很奇怪,因为大多数遥测工作正常)

这是我们设置 telemetryClient 的代码:

public void Initialize()
        {
            if (_initialized) return;
            lock (_initializationLock)
            {
                if (_initialized) return;
                var iKey = ApplicationInsightsConfiguration.InstrumentationKey;

                //Call this even if ikey is null or empty
                MonitoringSettings = new Settings(iKey);

                //If we don't have a key we can't do anything
                if (string.IsNullOrEmpty(iKey))
                {
                    Logger.Info($"No Application Insights telemetry key is available (Production flag: {SystemSettings.IsProductionServer})");
                    TelemetryConfiguration.Active.DisableTelemetry = true;
                    return;
                }

                //Set telemetry key
                TelemetryConfiguration.Active.InstrumentationKey = iKey;

                //Set up custom telemetry initializers
                //We need to initialize it before we send the non-prod custom event, so that the event will contain all required info
                SetUpTelemetryInitializers();

                //Disable telemetry reporting if it is not production instance
                //If overridden in web.ApplicationInsightsConfiguration explicitly, allow telemetry reporting
                if (ApplicationInsightsConfiguration.ForceSendTelemetry)
                {
                    Client.TrackEvent("ForceSendTelemetry enabled.");
                }

                //Set up custom telemetry filtration
                SetUpTelemetryProcessors();

                //send the license information if it has not already been sent for this Middleware instance startup
                SendLicenseConfiguration();

                //Track the event
                Client.TrackEvent("Telemetry Opt In", MonitoringSettings.GetAsDictionary());

                _initialized = true;
            }
        }

值得一提的是,如果我将遥测 key 添加到应用程序配置中,则跟踪监听器可以工作...出于某种原因,当我们以编程方式添加它时,它缺少对具有正确检测的原始遥测配置对象的引用关键,我认为发生这种情况是因为我正在使用 appinsights 的监听器创建一个新的 TraceSource 对象,其中包含一个新的配置实例。

最佳答案

谢谢Jiayao 。将您的建议作为答案发布以帮助其他社区成员。

使应用程序能够跟踪代码执行并将跟踪消息与其源关联的属性。

public class TraceSource

下面的代码可以帮助您理解 Tracesource 类并演示开关和过滤器的用法。

// The following configuration file can be used with this sample.
// When using a configuration file #define ConfigFile.
//            <source name="TraceTest" switchName="SourceSwitch" switchType="System.Diagnostics.SourceSwitch" >
//                    <add name="console" type="System.Diagnostics.ConsoleTraceListener" initializeData="false" />
//                    <remove name ="Default" />
//            <!-- You can set the level at which tracing is to occur -->
//            <add name="SourceSwitch" value="Warning" />
//            <!-- You can turn tracing off -->
//            <!--add name="SourceSwitch" value="Off" -->
//        <trace autoflush="true" indentsize="4"></trace>
#define TRACE
//#define ConfigFile

using System;
using System.Collections;
using System.Diagnostics;
using System.Reflection;
using System.IO;
using System.Security.Permissions;

namespace Testing
{
    class TraceTest
    {
        // Initialize the trace source.
        static TraceSource ts = new TraceSource("TraceTest");
        [SwitchAttribute("SourceSwitch", typeof(SourceSwitch))]
        static void Main()
        {
            try
            {
                // Initialize trace switches.
#if(!ConfigFile)
                SourceSwitch sourceSwitch = new SourceSwitch("SourceSwitch", "Verbose");
                ts.Switch = sourceSwitch;
                int idxConsole = ts.Listeners.Add(new System.Diagnostics.ConsoleTraceListener());
                ts.Listeners[idxConsole].Name = "console";
#endif
                DisplayProperties(ts);
                ts.Listeners["console"].TraceOutputOptions |= TraceOptions.Callstack;
                ts.TraceEvent(TraceEventType.Warning, 1);
                ts.Listeners["console"].TraceOutputOptions = TraceOptions.DateTime;
                // Issue file not found message as a warning.
                ts.TraceEvent(TraceEventType.Warning, 2, "File Test not found");
                // Issue file not found message as a verbose event using a formatted string.
                ts.TraceEvent(TraceEventType.Verbose, 3, "File {0} not found.", "test");
                // Issue file not found message as information.
                ts.TraceInformation("File {0} not found.", "test");
                ts.Listeners["console"].TraceOutputOptions |= TraceOptions.LogicalOperationStack;
                // Issue file not found message as an error event.
                ts.TraceEvent(TraceEventType.Error, 4, "File {0} not found.", "test");
                // Test the filter on the ConsoleTraceListener.
                ts.Listeners["console"].Filter = new SourceFilter("No match");
                ts.TraceData(TraceEventType.Error, 5,
                    "SourceFilter should reject this message for the console trace listener.");
                ts.Listeners["console"].Filter = new SourceFilter("TraceTest");
                ts.TraceData(TraceEventType.Error, 6,
                    "SourceFilter should let this message through on the console trace listener.");
                ts.Listeners["console"].Filter = null;
                // Use the TraceData method.
                ts.TraceData(TraceEventType.Warning, 7, new object());
                ts.TraceData(TraceEventType.Warning, 8, new object[] { "Message 1", "Message 2" });
                // Activity tests.
                ts.TraceEvent(TraceEventType.Start, 9, "Will not appear until the switch is changed.");
                ts.Switch.Level = SourceLevels.ActivityTracing | SourceLevels.Critical;
                ts.TraceEvent(TraceEventType.Suspend, 10, "Switch includes ActivityTracing, this should appear");
                ts.TraceEvent(TraceEventType.Critical, 11, "Switch includes Critical, this should appear");
                ts.Flush();
                ts.Close();
                Console.WriteLine("Press any key to exit.");
                Console.Read();
            }
            catch (Exception e)
            {
                // Catch any unexpected exception.
                Console.WriteLine("Unexpected exception: " + e.ToString());
                Console.Read();
            }
        }
        public static void DisplayProperties(TraceSource ts)
        {
            Console.WriteLine("TraceSource name = " + ts.Name);
            Console.WriteLine("TraceSource switch level = " + ts.Switch.Level);
            Console.WriteLine("TraceSource switch = " + ts.Switch.DisplayName);
            SwitchAttribute[] switches = SwitchAttribute.GetAll(typeof(TraceTest).Assembly);
            for (int i = 0; i < switches.Length; i++)
            {
                Console.WriteLine("Switch name = " + switches[i].SwitchName);
                Console.WriteLine("Switch type = " + switches[i].SwitchType);
            }
#if(ConfigFile)
            // Get the custom attributes for the TraceSource.
            Console.WriteLine("Number of custom trace source attributes = "
                + ts.Attributes.Count);
            foreach (DictionaryEntry de in ts.Attributes)
                Console.WriteLine("Custom trace source attribute = "
                    + de.Key + "  " + de.Value);
            // Get the custom attributes for the trace source switch.
            foreach (DictionaryEntry de in ts.Switch.Attributes)
                Console.WriteLine("Custom switch attribute = "
                    + de.Key + "  " + de.Value);
#endif
            Console.WriteLine("Number of listeners = " + ts.Listeners.Count);
            foreach (TraceListener traceListener in ts.Listeners)
            {
                Console.Write("TraceListener: " + traceListener.Name + "\t");
                // The following output can be used to update the configuration file.
                Console.WriteLine("AssemblyQualifiedName = " +
                    (traceListener.GetType().AssemblyQualifiedName));
            }
        }
    }
}

有关更多信息,请验证 TraceSource Class .

关于asp.net - System.Diagnostics.TraceSource 未将数据发送到 Application Insights,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69051039/

相关文章:

azure - 限制 Azure 存储容器的初始大小

javascript - Azure Function + Javascript如何获取我在post请求中传递的数据?

.net - 是否可以在具有 SOAP 对象的服务上使用多态性?

c# - 支持 Ajax 的 WCF 服务 - 实现观察者设计模式

c# - N 层 ASP.NET 应用程序 : One class library for all my layers or one class library for each layer?

c# - 类库中的 HttpContext.GetGlobalResourceObject 始终为 null

javascript - 缩小 signalr/hubs 文件

c# - 在没有标题的情况下将 CSV 文件读入数据集

azure - 使用 Azure 流分析进行简单的数据传递

.net - WCF内网安全配置