Application Insights与AKS集成求助:.NET6函数应用无日志上报
AKS上.NET6函数应用集成Application Insights问题排查与解决
问题1:启动时依赖版本冲突错误
错误信息
[2023-03-11T08:28:14.976Z] A host error has occurred during startup operation '22b81d60-dbcc-4a99-a88a-4cb968081c94'. [2023-03-11T08:28:14.978Z] TestPOC-AF: Could not load file or assembly 'Microsoft.Extensions.Configuration.Abstractions, Version=7.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'. The system cannot find the file specified.
原因
Microsoft.NET.Sdk.Functions 4.1.3基于.NET6构建,依赖6.x版本的Microsoft.Extensions系列组件,但你引入了Microsoft.Extensions.Hosting 7.0.1(.NET7版本),导致版本冲突,宿主无法找到匹配的程序集。
解决方案
修改包配置,将Microsoft.Extensions.Hosting降级到与.NET6兼容的版本(如6.0.1),确保所有Microsoft.Extensions相关包版本一致:
<ItemGroup> <!-- 注释掉AspNetCore包,函数应用用WorkerService --> <!-- <PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.21.0" /> --> <PackageReference Include="Microsoft.ApplicationInsights.Kubernetes" Version="6.1.0" /> <PackageReference Include="Microsoft.ApplicationInsights.WorkerService" Version="2.21.0" /> <PackageReference Include="Microsoft.NET.Sdk.Functions" Version="4.1.3" /> <PackageReference Include="Microsoft.Azure.Functions.Extensions" Version="1.1.0" /> <PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.17.2" /> <!-- 降级到.NET6兼容版本 --> <PackageReference Include="Microsoft.Extensions.Hosting" Version="6.0.1" /> </ItemGroup>
问题2:Application Insights日志不上报
原因分析
- 手动创建
TelemetryClient的方式不符合Azure Functions集成规范,宿主会管理自己的Telemetry实例,手动注册的实例无法和宿主日志系统联动。 - 未正确启用Application Insights Worker Service集成,日志提供者配置不完整。
- AKS环境下缺少读取Pod元数据的权限,导致Kubernetes信息无法enrich到遥测数据中。
解决方案
1. 修改Startup.cs配置,使用官方集成方式
移除手动创建TelemetryClient的代码,改用官方扩展方法完成配置:
using Microsoft.Azure.Functions.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection; using Test.Azure.Functions.Articles.Config; using System; using Microsoft.ApplicationInsights.Extensibility; using Test.Azure.Functions.Telemetry; using Microsoft.Extensions.Logging; [assembly: FunctionsStartup(typeof(Startup))] namespace Test.Azure.Functions.Articles.Config { public class Startup : FunctionsStartup { public override void Configure(IFunctionsHostBuilder builder) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } // 1. 启用Application Insights Worker Service集成,自动配置TelemetryClient builder.Services.AddApplicationInsightsTelemetryWorkerService(options => { // 直接配置InstrumentationKey,或通过环境变量读取(推荐生产环境用环境变量) options.InstrumentationKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; }); // 2. 启用AKS环境信息 enrichment,自动添加Pod/Namespace等元数据 builder.Services.AddApplicationInsightsKubernetesEnricher(LogLevel.Debug); // 3. 保留自定义Telemetry初始化器(可选,AKS enricher已自带基础逻辑) builder.Services.AddSingleton<ITelemetryInitializer, KubernetesTelemetryInitializer>(); // 4. 确保日志通过Application Insights输出 builder.Services.AddLogging(loggingBuilder => { loggingBuilder.AddApplicationInsights(); loggingBuilder.SetMinimumLevel(LogLevel.Information); }); } } }
2. 简化自定义TelemetryInitializer(可选)
Microsoft.ApplicationInsights.Kubernetes已经自带Kubernetes环境信息的初始化逻辑,若无需额外自定义,可直接移除自己的KubernetesTelemetryInitializer;若保留,需确保AKS Pod中已正确设置MY_POD_NAMESPACE环境变量。
3. 配置AKS权限读取K8s元数据
Application Insights Kubernetes包需要从K8s API获取Pod信息,需为Pod的ServiceAccount配置view权限:
# 示例ServiceAccount、Role及绑定配置 apiVersion: v1 kind: ServiceAccount metadata: name: function-app-sa namespace: microservices-dev --- apiVersion: rbac.authorization.k8s.io/v1 kind: Role metadata: name: function-app-role namespace: microservices-dev rules: - apiGroups: [""] resources: ["pods", "nodes"] verbs: ["get", "list", "watch"] --- apiVersion: rbac.authorization.k8s.io/v1 kind: RoleBinding metadata: name: function-app-rolebinding namespace: microservices-dev subjects: - kind: ServiceAccount name: function-app-sa roleRef: kind: Role name: function-app-role apiGroup: rbac.authorization.k8s.io
在Deployment中指定该ServiceAccount:
spec: template: spec: serviceAccountName: function-app-sa
4. 用ILogger输出日志
在函数代码中通过ILogger输出日志,确保日志能被Application Insights捕获:
public class MyFunction { private readonly ILogger<MyFunction> _logger; public MyFunction(ILogger<MyFunction> logger) { _logger = logger; } [FunctionName("MyFunction")] public async Task<IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req) { _logger.LogInformation("函数执行开始"); // 业务逻辑 _logger.LogError("模拟错误日志"); return new OkObjectResult("执行完成"); } }
验证步骤
- 重新构建并部署函数应用到AKS
- 查看容器日志,确认无启动错误,且出现
Application Insights Kubernetes injected the service successfully日志 - 触发函数执行,等待5-10分钟后查看Application Insights的日志和事件页面,确认数据已上报
内容的提问来源于stack exchange,提问作者suraj_123
相关产品推荐
相关产品推荐

