You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript Azure Durable Functions:如何在ActivityHandler中使用Context?

问题

使用Azure Functions、TypeScript及编程模型V4开发持久化函数链式调用时,编排器可正常调用活动函数,但在ActivityHandler中无法获取context对象,无法使用context.log/warn/error等日志方法。尝试修改ActivityHandler签名、调整类型定义、添加extraInputs选项均出现兼容性报错,请问如何实现类似普通Azure Functions的日志输出,对应的最佳实践是什么?

相关代码示例

编排器调用活动

const moveToMainActivityName = 'moveToMainContainerActivity';    
yield context.df.callActivity(moveToMainActivityName, itemsToProcess);

活动定义

const moveToMainContainerActivity: ActivityHandler = async (records: any[])=>{
  //do stuff
    context.error(`Failed to process items: ${error.message}`);
  //other stuff
};

活动注册

df.app.activity(moveToMainActivityName, { handler: moveToMainContainerActivity });

解决方案

基础日志输出方案

在编程模型V4的Durable Functions活动函数中,无需通过context对象打日志,直接使用全局console对象即可。Azure Functions会自动捕获console.log/warn/error的输出,整合到函数日志系统中,效果和普通函数的context.log完全一致。

修改后的活动函数代码:

const moveToMainContainerActivity: ActivityHandler = async (records: any[])=>{
  try {
    // 业务逻辑处理
  } catch (error) {
    console.error(`Failed to process items: ${(error as Error).message}`);
    throw error; // 抛出异常让编排器感知失败状态
  }
};

进阶:获取完整运行时上下文

如果需要访问环境变量、绑定数据等更多运行时信息,可以通过InvocationContext参数获取,调整活动函数签名即可:

import { InvocationContext } from "@azure/functions";

const moveToMainContainerActivity: ActivityHandler = async (records: any[], context: InvocationContext)=>{
  context.log.info("开始处理记录");
  try {
    // 业务逻辑
  } catch (error) {
    context.log.error(`处理失败: ${(error as Error).message}`);
    throw error;
  }
};

注意:使用InvocationContext需确保@azure/functions包版本不低于v4.0.0,活动注册代码无需修改,框架会自动注入该参数。

最佳实践总结

  • 优先使用console系列方法输出基础日志,避免类型兼容性问题
  • 需要访问运行时信息时,使用InvocationContext参数替代旧版context
  • 活动函数中抛出异常时,务必保留日志输出,便于后续排查问题

内容的提问来源于stack exchange,提问作者Daanvl

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 08:23:14