问题描述
基于.NET Core的Function App如果配置了Application Insights之后,每有一个函数被执行,则在Application Insights中的Logs中的trace里都可以查询到函数的执行启动,执行结束的信息。类似如下的日志,
由于这类日志产生的条目过多且没有包含业务日志,所以在不影响其他业务或异常日志的情况下,是否可以不收集此类信息呢?
问题原因
Application Insights收集日志信息是根据在Azure Function中的host.json配置而决定的。如以下内容:
{
"logging": {
"fileLoggingMode": "always",
"logLevel": {
"default": "Information",
"Host.Results": "Error",
"Function": "Error",
"Host.Aggregator": "Trace"
}
}
}
- 对于
Host.Results
或Function
的日志,仅记录Error
或更高级别的事件。 - 对于
Host.Aggregator
的日志,记录所有生成的指标 (Trace
)。 - 对于所有其他日志(包括用户日志),仅记录
Information
级别及更高级别的事件。
而对于日志级别的分类,则可以参考下表:
为每个日志分配日志级别。 该值是表示相对重要性的整数:
所以根据以上的基础信息,在Application Insights的Trace表中,我们查看到函数执行日志的Category和LogLevel,这样就可以针对性的设置收集日志的参数。
由此我们可以得出: Executing和Executed两个记录在function层面对应的category和log level分别是Function.Function1 与Information
解决方式
根据以上的分析,只要在host.json中限制Loglevel和Category就可以实现过滤不需要的日志。
- 通过修改Function.Funciton1为Warning的信息,则过滤掉了waring级别以下的日志(如本文开头提及的information)。
- 通过设置Function.Function1.User为Information信息,则可以保证通过代码记录的inforamtion级别及以上的日志可以发送到Application Insights。
查询Application Insights中生成的日志记录,可以看到是没有Function.Function1的information的日志的
附上在Application Insights的Traces表中查询到以上记录的语句
traces | where timestamp > ago(30m) | extend category = customDimensions.Category | extend logLevel = customDimensions.LogLevel | project timestamp, category, logLevel, message | order by timestamp desc
参考资料
如何为 Azure Functions 配置监视: https://docs.azure.cn/zh-cn/azure-functions/configure-monitoring?tabs=v2