Azure Function(.NET 7)日志冗余:保留Info级应用日志并屏蔽HTTP请求日志
解决Azure Function(.NET 7)中SecretClient/BlobServiceClient HTTP日志过多的问题
核心原因
你之前的过滤规则未生效,是因为SecretClient和BlobServiceClient使用的HttpClient带有特定的命名空间后缀,而非通用的System.Net.Http.HttpClient类别。此外,Azure SDK的底层请求日志还会通过Azure.Core命名空间输出。
解决方案
方案1:通过代码精准过滤特定客户端的HTTP日志
修改日志过滤规则,针对SecretClient和BlobServiceClient对应的HttpClient类别设置日志级别为Warning或更高:
.ConfigureLogging(builder => { // 过滤SecretClient的HTTP请求日志 builder.AddFilter("System.Net.Http.HttpClient.Azure.Security.KeyVault.Secrets.SecretClient", LogLevel.Warning); // 过滤BlobServiceClient的HTTP请求日志 builder.AddFilter("System.Net.Http.HttpClient.Azure.Storage.Blobs.BlobServiceClient", LogLevel.Warning); // 可选:过滤Azure.Core底层的请求详细日志 builder.AddFilter("Azure.Core", LogLevel.Warning); })
方案2:通过host.json配置(推荐,适配本地和Azure环境)
Azure Function优先读取host.json的日志配置,直接在该文件中添加规则,无需修改代码:
{ "logging": { "applicationInsights": { "samplingSettings": { "isEnabled": true, "excludedTypes": "Request" } }, "logLevel": { "Default": "Information", "System.Net.Http.HttpClient.Azure.Security.KeyVault.Secrets.SecretClient": "Warning", "System.Net.Http.HttpClient.Azure.Storage.Blobs.BlobServiceClient": "Warning", "Azure.Core": "Warning" } } }
方案3:禁用Azure SDK的HTTP日志追踪
如果不需要任何Azure SDK的HTTP请求日志,可以直接关闭Azure.Core的日志追踪:
// 注册SecretClient时配置 var secretClient = new SecretClient(new Uri("your-vault-uri"), new DefaultAzureCredential(), new SecretClientOptions { Diagnostics = { IsLoggingContentEnabled = false, IsLoggingEnabled = false } }); // 注册BlobServiceClient时配置 var blobServiceClient = new BlobServiceClient("your-storage-connection-string", new BlobClientOptions { Diagnostics = { IsLoggingContentEnabled = false, IsLoggingEnabled = false } });
验证方式
- 本地运行时,查看VS的输出窗口,确认SecretClient/BlobServiceClient的HTTP请求日志不再以Information级别输出
- Azure环境中,查看Application Insights的日志查询,筛选
severityLevel == 2(Information)时不会出现目标日志
内容的提问来源于stack exchange,提问作者mammoetsaus
相关产品推荐
相关产品推荐

