Azure函数应用配置:如何筛选Durable Function自定义日志
在App Insights中筛选Durable Function自定义日志的方法
以下几种方法可以帮你快速定位自定义函数里的日志,过滤掉系统生成的冗余日志:
1. 通过日志类别精准筛选
编写Durable Function代码时,我们通常会注入对应函数类的ILogger实例(比如ILogger<MyOrchestratorFunction>),这类日志的Category字段会自动关联到函数类全名。而系统日志的类别一般以Microsoft.*、DurableTask.*开头。
在App Insights的日志查询中使用Kusto语句筛选指定类别:
traces | where Category == "YourNamespace.YourFunctionClassName" // 替换为你的函数类别名称 | order by timestamp desc
如果多个自定义函数使用同一命名空间,也可以用模糊匹配:
traces | where Category startswith "YourNamespace." | order by timestamp desc
2. 给自定义日志添加专属标记筛选
写日志时主动添加自定义属性,之后通过该属性过滤:
方式一:直接在日志中附加属性
// 在函数代码中写入带自定义属性的日志 _logger.LogInformation("完成用户 {UserId} 的请求处理", userId, new Dictionary<string, object> { { "CustomLogTag", "FunctionBusinessLog" } });
方式二:使用Scope批量添加属性
如果某个代码块内的所有日志都需要标记,可以用BeginScope批量设置:
using (_logger.BeginScope(new Dictionary<string, object> { { "CustomLogTag", "FunctionBusinessLog" } })) { _logger.LogInformation("开始执行编排流程"); // 其他日志语句... }
之后在App Insights中通过自定义属性筛选:
traces | where customDimensions.CustomLogTag == "FunctionBusinessLog" | order by timestamp desc
3. 调整Host.json减少系统日志输出
通过配置Host.json的日志级别,降低系统日志的输出量,从源头减少干扰:
{ "logging": { "applicationInsights": { "samplingSettings": { "isEnabled": true } }, "logLevel": { // 自定义函数命名空间下的日志输出Information及以上级别 "YourNamespace.*": "Information", // 系统相关日志仅输出Warning及以上级别 "Microsoft.*": "Warning", "DurableTask.*": "Warning" } } }
这样系统只会输出较严重的警告或错误日志,配合前面的筛选方法,能更高效找到自定义日志。
内容的提问来源于stack exchange,提问作者Luis M
相关产品推荐
相关产品推荐

