如何使用Azure触发器函数向Azure Application Insights写入自定义日志?
使用Azure函数触发器创建自定义日志并上报至Application Insights
前提条件
- 已创建Azure函数应用,且已关联Application Insights资源(创建时可直接绑定,或事后在门户配置)
- 本地开发环境已配置Azure Functions开发工具(如VS Code扩展、Visual Studio)
C# Timer触发器示例
Azure Functions的.NET运行时已默认集成Application Insights日志推送,直接使用ILogger即可完成自定义日志上报,无需额外引入SDK。
using Microsoft.Azure.WebJobs; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; namespace CustomLogsDemo { public class TimerTriggerLogger { [FunctionName("TimerTrigger_CustomLogs")] public void Run([TimerTrigger("0 */5 * * * *")] TimerInfo timer, ILogger log) { // 基础信息日志 log.LogInformation("Timer触发器启动执行,UTC时间: {CurrentTime}", DateTime.UtcNow); // 用BeginScope添加自定义维度,方便在AI中筛选 using (log.BeginScope(new Dictionary<string, object> { {"FunctionCategory", "ScheduledTask"}, {"ExecutionBatchId", Guid.NewGuid().ToString()} })) { log.LogTrace("业务初始化完成,准备执行数据同步"); log.LogWarning("检测到资源使用率达75%,建议扩容"); try { // 模拟业务逻辑异常 int divideResult = 10 / 0; } catch (DivideByZeroException ex) { // 上报错误日志,包含异常堆栈 log.LogError(ex, "数据同步失败:{ErrorMessage}", ex.Message); } } log.LogInformation("Timer触发器执行结束"); } } }
说明
ILogger的不同日志级别(Trace/Info/Warning/Error)会对应Application Insights中的severityLevel字段BeginScope添加的自定义维度会存入AI日志的customDimensions字段,可用于Kusto查询筛选
Python HTTP触发器示例
Python运行时同样内置AI日志集成,使用标准logging模块即可完成上报,无需额外安装包。
import logging import azure.functions as func def main(req: func.HttpRequest) -> func.HttpResponse: logging.info("HTTP触发器收到请求,开始处理流程") # 上报带自定义维度的日志 logging.getLogger().info( "用户请求处理中", extra={ "custom_dimensions": { "RequestMethod": req.method, "RequestPath": req.path, "UserSessionId": "session_abc123" } } ) try: name = req.params.get("name") if not name: raise ValueError("未提供必填参数name") return func.HttpResponse(f"Hello, {name}!") except Exception as ex: # 上报错误日志,包含完整异常信息 logging.error(f"请求处理失败: {str(ex)}", exc_info=True) return func.HttpResponse("服务器内部错误", status_code=500) logging.info("HTTP触发器请求处理完成")
说明
- 通过
extra={"custom_dimensions": {...}}添加自定义属性,这些属性会出现在AI日志的customDimensions中 exc_info=True会将异常的堆栈信息一并上报到Application Insights
验证日志上报
- 登录Azure门户,打开对应的Application Insights资源
- 进入**日志(Logs)**页面,使用Kusto查询查看自定义日志:
traces | where customDimensions.FunctionCategory == "ScheduledTask" or customDimensions.RequestMethod == "GET" | order by timestamp desc | limit 50 - 也可在**搜索(Search)**页面按日志级别、关键字筛选日志条目
注意事项
- 确认函数应用的
APPINSIGHTS_INSTRUMENTATIONKEY配置正确(在函数应用的配置->应用程序设置中查看) - 日志级别控制:可通过
host.json调整日志输出级别,示例:{ "logging": { "applicationInsights": { "samplingSettings": { "isEnabled": true } }, "logLevel": { "CustomLogsDemo": "Information" } } } - 采样配置:默认AI会对日志采样,若需全量上报,可将
samplingSettings.isEnabled设为false(注意可能增加费用)
内容的提问来源于stack exchange,提问作者virat_kohli
相关产品推荐
相关产品推荐

