无法将Trace事件记录到Application Insights的问题求助
Looks like the key issue here is that you’re still using the TextWriterTraceListener (which writes logs to a local file) instead of the Application Insights-specific trace listener from the NuGet package you installed. Let’s fix that step by step:
1. Verify the correct NuGet package is installed
First, double-check that Microsoft.ApplicationInsights.TraceListener is installed in your project (you mentioned you have it, but confirm it’s the latest compatible version for your .NET Framework runtime).
2. Update your web.config trace listener configuration
Replace your existing <system.diagnostics> section with this, which uses the Application Insights trace listener instead of the text writer one:
<system.diagnostics> <trace autoflush="true" indentsize="4"> <listeners> <add name="aiListener" type="Microsoft.ApplicationInsights.TraceListener.ApplicationInsightsTraceListener, Microsoft.ApplicationInsights.TraceListener" /> <!-- Keep the Default listener if you still want logs in the console/traditional locations, or remove it if you only want AI --> <!-- <remove name="Default" /> --> </listeners> </trace> </system.diagnostics>
- Key changes:
- Swapped out
TextWriterTraceListenerforApplicationInsightsTraceListener(the fully qualified type name is critical here) - Set
autoflush="true"to ensure logs are sent to AI immediately (if you leave this asfalse, you’ll need to callTrace.Flush()manually after writing traces) - Keep the
Defaultlistener if you want traces to still appear in standard outputs like the console, or remove it to route logs only to Application Insights.
- Swapped out
3. Ensure your Application Insights instrumentation key is configured
Make sure your web.config includes the Application Insights section with your valid instrumentation key (this is usually added automatically during AI setup, but add it if missing):
<configuration> <applicationInsights xmlns="http://schemas.microsoft.com/ApplicationInsights/2013/Settings"> <instrumentationKey>YOUR_INSTRUMENTATION_KEY_HERE</instrumentationKey> </applicationInsights> <!-- ... other configuration sections ... --> </configuration>
4. Test your trace calls again
Now when you run your existing trace code:
Trace.WriteLine("Api v1 called by user"); Trace.TraceWarning("Tracking warning via AI");
These events should appear in Application Insights under the Traces section. You can find them in the Logs with a query like traces | where message contains "Api v1".
Why your original setup didn’t work
Your initial web.config was configured to write traces to a local file (TextWriterOutput.log) via TextWriterTraceListener—it had no connection to Application Insights at all. The Microsoft.ApplicationInsights.TraceListener package provides the specific listener that bridges System.Diagnostics.Trace calls to Application Insights telemetry.
内容的提问来源于stack exchange,提问作者learntogrow-growtolearn

