设置性能分析

了解如何在应用程序中启用性能分析(如果尚未设置)。

通过性能分析,Sentry 通过在各种环境中采样程序的调用栈来跟踪软件的性能。此功能收集关于代码的功能级信息,使你能够微调程序的性能。Sentry 的性能分析器捕获函数调用及其确切位置,对它们进行聚合,并显示程序中最常见的代码路径。这突出了你可以优化的区域,以帮助提高代码性能和用户满意度,同时降低成本。

Python 性能分析在 SDK 版本 1.18.0 及以上版本中稳定。

Copied
import sentry_sdk

def profiles_sampler(sampling_context):
    # ...
    # return a number between 0 and 1 or a boolean

sentry_sdk.init(
    dsn="https://examplePublicKey@o0.ingest.sentry.io/0",
    traces_sample_rate=1.0,

    # To set a uniform sample rate
    # Set profiles_sample_rate to 1.0 to profile 100%
    # of sampled transactions.
    # We recommend adjusting this value in production,
    profiles_sample_rate=1.0,

    # Alternatively, to control sampling dynamically
    profiles_sampler=profiles_sampler
)

profiles_sample_rate 设置是相对于 traces_sample_rate 设置的。

要使性能分析正常工作,您必须首先通过 traces_sample_rate 启用 Sentry 的跟踪(如上面的示例所示)。请阅读我们的跟踪设置文档以了解如何配置采样。如果您将采样率设置为 1.0,则所有事务都将被捕获。

在 SDK 版本 1.17.0 及更早版本中,性能分析是实验性的。了解如何升级此处

此功能当前处于 Beta 阶段。Beta 功能仍在开发中,可能存在 bug。我们意识到其中的讽刺意味。

(新版本 2.13.0)

当前的性能分析实现会在 30 秒后自动停止分析器(除非您手动提前停止)。显然,这种限制使得难以获得应用程序执行的完整覆盖率。我们现在提供了一个实验性的持续模式,其中性能分析数据会在运行时定期上传,没有对分析器运行时间的限制。

要开始持续性能分析,您可以直接使用 sentry_sdk.profiler.start_profilersentry_sdk.profiler.stop_profiler 启动和停止分析器。

如果您之前设置了 profiles_sample_rateprofilers_sampler 以使用基于事务的性能分析,必须从配置中移除这些代码行以使用持续性能分析。

Copied
import sentry_sdk

sentry_sdk.init(
    dsn="https://examplePublicKey@o0.ingest.sentry.io/0",
    traces_sample_rate=1.0,
)

sentry_sdk.profiler.start_profiler()

# run some code here

sentry_sdk.profiler.stop_profiler()

对于某些应用程序(如 Web 服务器),在每个进程中调用 sentry_sdk.profiler.start_profiler 可能比较困难。相反,您可以使用 continuous_profiling_auto_start 选项,以便在事务启动时自动启动持续性能分析器。

Copied
import sentry_sdk

sentry_sdk.init(
    dsn="https://examplePublicKey@o0.ingest.sentry.io/0",
    traces_sample_rate=1.0,
    _experiments={
      "continuous_profiling_auto_start": True,
    },
)

这些新的 API 不提供任何采样功能——每次调用启动分析器时都会启动它,同样适用于您配置的启动配置文件。如果您希望减少运行的配置文件数量,必须在调用点进行处理。

持续性能分析对组织的计费结构有影响。此功能仅适用于 2024 年 6 月 5 日之后注册的订阅计划。