System.Diagnostics.TraceSource没有向Application Insights发送数据.&l



我在我的项目中设置了应用程序见解,它工作正常,它将数据发送到Azure而没有任何问题,现在我试图使用System.Diagnostics.SourceTrace将一些跟踪日志发送到遥测中,这是在Webhost应用程序中引用的内部nuget包中实现的(此nuget包不包含对应用程序见解的引用),事情是……由于某种原因,它只是没有到达代码,好吧,它做到了,但它没有同时,当我在输出窗口中调试时,我可以看到当它到达system . diagnostics . traceevent()方法时创建了一个事件,但它显示如下

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

这让我认为,由于某种原因遥测客户端正在失去对仪器关键或类似的东西的参考,我不确定如何解决这个问题,因为它只发生在那里。

编辑:这是我们如何设置跟踪源的,这些代码存在于网络中。webhost应用程序的配置文件,它引用了另一个项目,该项目引用了日志记录发生的nuget包。

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

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

下面是我们设置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;
}
}

值得一提的是,如果我将遥测键添加到应用程序配置中,tracelistener就会工作…由于某种原因,当我们以编程方式添加它时,它丢失了对原始遥测配置对象的引用,并使用正确的仪表键,我认为这是因为我正在使用appinsights的侦听器创建一个新的TraceSource对象,其中包括一个新的配置实例。

谢谢嘉耀。把你的建议作为答案来帮助其他社区成员。

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

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类。

最新更新