Xamarin应用无法实例化Azure Application Insights TelemetryClient报错
问题说明
在Xamarin应用中运行相关代码时触发异常,需排查代码问题,判断是否属于兼容性问题。
问题代码
string key = configurationWrapper.GetValue<string>("ApplicationInsights:InstrumentationKey"); TelemetryConfiguration config = TelemetryConfiguration.CreateDefault(); // 此处抛出异常!!!!! config.InstrumentationKey = key; _telemetryClient = new TelemetryClient(config);
补充异常详情
异常在调用TelemetryConfiguration.CreateDefault()方法时触发,类型为ArgumentNullException,提示path1参数不能为空,堆栈跟踪如下:
{System.ArgumentNullException: Value cannot be null. Parameter name: path1 at System.IO.Path.Combine (System.String path1, System.String path2) [0x00003] in /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/mcs/class/corlib/System.IO/Path.cs:102 at Microsoft.ApplicationInsights.Extensibility.Implementation.Tracing.SelfDiagnostics.SelfDiagnosticsConfigParser.TryGetConfiguration (System.String& logDirectory, System.Int32& fileSizeInKB, System.Diagnostics.Tracing.EventLevel& logLevel) [0x00017] in /_/BASE/src/Microsoft.ApplicationInsights/Extensibility/Implementation/Tracing/SelfDiagnostics/SelfDiagnosticsConfigParser.cs:49 }
从堆栈可以定位,异常源于Application Insights自诊断配置解析逻辑调用Path.Combine时传入了空参数。
问题结论
- 上述业务代码本身不存在逻辑错误,该异常属于Microsoft.ApplicationInsights库和Xamarin(尤其是Mono安卓运行时)的兼容性问题。
- 具体触发逻辑:
TelemetryConfiguration.CreateDefault()初始化时会默认加载自诊断日志模块,模块内的SelfDiagnosticsConfigParser需要拼接日志文件存储路径,会先读取当前运行环境的默认日志目录作为Path.Combine的第一个路径参数。但触发异常版本的Application Insights没有做Xamarin移动端平台的路径适配,在安卓Mono运行时下拿不到有效的默认日志目录,获取到的参数值为null,调用Path.Combine时直接触发空参数异常。
解决方法
- 优先升级Application Insights到官方修复了Xamarin平台适配问题的版本,选择明确标注支持移动端运行环境的发行版。
- 若暂时无法升级依赖,可以在调用
CreateDefault()方法前,手动关闭自诊断日志功能,或者手动给自诊断模块指定一个当前应用有权限访问的合法内部存储路径作为日志目录,避免传入空值触发异常。
内容的提问来源于stack exchange,提问作者Jackson Mourão
相关产品推荐
相关产品推荐

