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

如何为TaskWeaver插件添加可正常生效的调试语句?

问题

开发TaskWeaver插件时,调试语句无法正常输出:

  • print语句无效果,因为插件由代码解释器运行而非直接通过终端执行
  • 自行配置logging模块后,日志既不写入文件也不显示在控制台

附上相关代码与配置:

插件代码

from typing import Any, Dict
from taskweaver.plugin import Plugin, register_plugin
import logging
from logging.handlers import RotatingFileHandler

# Set up logging to file
logging.basicConfig(
    filename='sample.log',
    filemode='a',
    format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s',
    datefmt='%H:%M:%S',
    level=logging.DEBUG
)

# Set up logging to console
console = logging.StreamHandler()
console.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
console.setFormatter(formatter)
logging.getLogger('').addHandler(console)

# Example usage
logging.info("This should log to both console and file.")


@register_plugin
class TestPlugin(Plugin):
    def __call__(self, text: str):
        log_file = open("log.txt", "w")
        log_file.write("The plugin is called with text: " + text)
        logging.info("The plugin is called with text: " + text)
        return text + " from test plugin after setting up logs"

if __name__ == "__main__":
    from taskweaver.plugin.context import temp_context

    with temp_context() as temp_ctx:
        render = TestPlugin(name="test_plugin", ctx=temp_ctx, config={})
        print(render(text="hello world!"))

配置文件 test_plugin.yaml

name: test_plugin
enabled: true
required: true
description: >-
  This plugin is a test plugin for the OpenTelemetry Collector

parameters:
  - name: text
    type: string
    required: true
    description: >-
      This is a text parameter

returns:
  - name: text
    type: string
    description: >-
      This is a text return
解决方案

TaskWeaver的插件运行环境已封装统一的日志系统,自定义logging配置会被环境覆盖,直接使用插件基类Plugin提供的logger属性即可实现调试输出:

  1. 移除所有自定义的logging配置代码,包括logging.basicConfig、StreamHandler相关逻辑
  2. 在插件类中通过self.logger调用日志方法,支持debug/info/warn/error等常用级别

修改后的插件代码:

from typing import Any, Dict
from taskweaver.plugin import Plugin, register_plugin

@register_plugin
class TestPlugin(Plugin):
    def __call__(self, text: str):
        # 使用插件自带的logger输出日志
        self.logger.info("The plugin is called with text: %s", text)
        self.logger.debug("Debug message from test plugin")
        
        # 若需写入自定义日志文件,建议用工作目录绝对路径避免权限问题
        log_path = self.ctx.work_dir / "log.txt"
        with open(log_path, "w") as f:
            f.write(f"The plugin is called with text: {text}")
            
        return text + " from test plugin after setting up logs"

if __name__ == "__main__":
    from taskweaver.plugin.context import temp_context

    with temp_context() as temp_ctx:
        render = TestPlugin(name="test_plugin", ctx=temp_ctx, config={})
        result = render(text="hello world!")
        print(result)

关键说明

  • TaskWeaver的Plugin基类初始化时会自动注入配置好的logger,日志会统一输出到TaskWeaver的控制台和默认日志文件中(路径在TaskWeaver工作目录下)
  • 自定义文件日志时,使用self.ctx.work_dir获取插件运行的工作目录,可避免路径权限或找不到文件的问题
  • 本地测试时的print和logging仅在直接运行脚本时生效,插件被代码解释器调用时必须依赖self.logger

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 06:21:10