Azure Portal中Application Insights未显示日志问题求助
问题排查与解决方案
已登录Azure App Insights,Visual Studio输出窗口可查看日志,但App Insights平台中无日志显示。使用NLog配置及控制台代码如上,将NLog配置移至app.config后,等待一小时仍无日志,可按以下步骤排查:
1. 验证Instrumentation Key/Connection String正确性
- 确保配置中
MyKey已替换为Azure App Insights实例的真实Instrumentation Key,可在Azure门户的App Insights概述页面获取。 - 推荐使用Connection String替代Instrumentation Key,更适配新特性,替换配置如下:
<target name="aiTarget" xsi:type="ApplicationInsightsTarget" > <connectionString>你的App Insights连接字符串</connectionString> <contextproperty name="threadid" layout="${threadid}" /> </target>
2. 启用NLog内部日志定位错误
- 修改NLog配置的
internalLogLevel为Debug,开启内部日志排查加载或发送问题:internalLogLevel="Debug" internalLogFile="c:\temp\nlog-internal.log" - 运行程序后查看
c:\temp\nlog-internal.log,检查是否存在组件加载失败、连接超时、权限不足等异常信息。
3. 确认NuGet包兼容性
- 确保已安装正确的NuGet包:
Microsoft.ApplicationInsights.NLogTarget,且其版本与Microsoft.ApplicationInsights核心包版本匹配,避免因版本不兼容导致目标初始化失败。 - 针对.NET Core/.NET 5+项目,需确认包版本适配当前框架版本。
4. 修正日志级别过滤规则
- 当前NLog规则设置
minlevel="Info",会过滤掉Logger.Trace()的日志,若需发送Trace级别日志,需调整规则:<rules> <logger name="*" minlevel="Trace" writeTo="aiTarget" /> </rules> - 若只需要发送Info及以上级别,
Logger.Trace()的日志本身就不会被发送,属于正常过滤。
5. 确保程序退出时日志完成发送
- 控制台程序运行结束过快时,异步发送的日志可能未完成传输就终止进程,需在Main方法末尾添加日志刷新逻辑:
static void Main(string[] args) { // 原有代码... foreach (string file in files) { Logger.Info("Hello world"); Logger.Trace("This should go to App insight"); Console.WriteLine("Processed file : " + file); } // 添加此行确保日志发送完成 NLog.LogManager.Shutdown(); }
6. 检查App Insights搜索配置
- 在Azure门户的App Insights搜索页面,调整时间范围为“过去24小时”,使用筛选条件
severityLevel:Info或severityLevel:Trace精准搜索日志,避免因时间范围设置过小或筛选条件错误导致看不到日志。
7. 修复app.config中的配置结构
- 若将NLog配置放在app.config中,需确保配置结构正确,包含
configSections声明:<configuration> <configSections> <section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog"/> </configSections> <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" autoReload="true" throwExceptions="false" internalLogLevel="Debug" internalLogFile="c:\temp\nlog-internal.log"> <!-- 原有extensions、targets、rules配置 --> </nlog> </configuration> - 缺少
configSections会导致NLog无法识别app.config中的NLog配置节点。
内容的提问来源于stack exchange,提问作者Not Not One
相关产品推荐
相关产品推荐

