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

如何配置New Relic Python Agent追踪服务中所有函数?

New Relic Python Agent 全函数追踪方案

针对你提到的需要追踪Python服务所有函数、避免逐个配置transaction_tracer.function_trace的问题,以下是可行的解决方案:

1. 使用通配符批量配置(快速但需注意性能)

New Relic Python Agent支持在transaction_tracer.function_trace中使用通配符匹配函数,实现批量追踪:

  • 追踪指定业务模块下的所有函数:
    transaction_tracer.function_trace = your_service_module.*
    
  • 追踪所有模块的函数(不推荐生产环境使用,会产生海量追踪数据,严重影响性能):
    transaction_tracer.function_trace = *.*
    

注意:这种方式会包含标准库和第三方依赖的函数调用,仅建议在调试阶段短期启用。

2. 自定义Instrumentation脚本(灵活可控)

编写自定义脚本批量为目标模块的函数添加追踪,既能覆盖业务代码的所有函数,又能排除不必要的第三方库:

示例自定义脚本(custom_instrumentation.py)

import newrelic.agent
import inspect

def instrument_target_module(module):
    # 遍历模块内的所有普通函数并添加追踪
    for name, obj in inspect.getmembers(module, inspect.isfunction):
        newrelic.agent.function_trace(obj)
    # 若需要追踪类中的方法,可添加以下逻辑
    for name, cls in inspect.getmembers(module, inspect.isclass):
        for method_name, method in inspect.getmembers(cls, inspect.isfunction):
            newrelic.agent.function_trace(method)

# 导入你的核心业务模块并应用追踪
import your_core_service_module
instrument_target_module(your_core_service_module)

在newrelic.ini中加载脚本

import = custom_instrumentation

3. 性能权衡说明

Python Agent默认不像Java Agent那样自动追踪大量方法,核心原因是Python的动态特性会导致全量追踪的性能损耗远高于Java。生产环境建议:

  • 仅对核心业务模块使用批量追踪
  • 配合transaction_tracer.transaction_threshold配置,只对慢事务采样全函数调用链:
    transaction_tracer.transaction_threshold = 0.5
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 08:52:49