检测缓存

了解如何手动检测代码以使用 Sentry 的 Caches 模块。

缓存可以加快数据检索速度,从而提高应用程序性能。因为应用程序可以从内存中获取数据(在最佳情况下),而不是从潜在较慢的数据层获取数据。缓存可以加速读取密集型工作负载的应用程序,如问答门户、游戏、媒体共享和社交网络。

Sentry 提供了一个缓存监控仪表板,可以自动检测流行的 Python 缓存设置(如 DjangoRedis 和即将推出的 memcached)。

如果您使用的是没有自动检测的自定义缓存解决方案,可以按照以下设置说明手动检测它,并使用 Sentry 查看缓存解决方案的性能。

为了让 Sentry 能够为您提供缓存性能的概览,您需要创建两个 Span——一个表示正在将某些内容放入缓存,另一个表示正在从缓存中获取某些内容。

确保在创建 Span 时有一个事务正在运行。如果您使用的是 Web 框架,这些事务将自动为您创建。有关更多信息,请参阅跟踪

有关可以设置的数据的详细信息,请参阅缓存模块开发者规范

如果您使用的是 DjangoRedis 或即将推出的 memcached 以外的任何内容,您需要按照以下步骤手动检测 缓存模块

如果您使用的缓存不支持上述自动检测,可以使用以下自定义检测说明来发出缓存 Span:

  1. 使用您正在使用的缓存库设置缓存值。
  2. 使用 with sentry_sdk.start_span(...) 包装应用程序中使用缓存值的部分。
  3. op 设置为 cache.put
  4. cache.item_size 设置为一个表示缓存项大小的整数。

(上述步骤在代码片段中有详细说明。)

Copied
import my_caching
import sentry_sdk

key = "myCacheKey123"
value = "The value I want to cache."

with sentry_sdk.start_span(op="cache.put") as span:
    # Set a key in your caching using your custom caching solution
    my_caching.set(key, value)

    # Describe the cache server you are accessing
    span.set_data("network.peer.address", "cache.example.com/supercache")
    span.set_data("network.peer.port", 9000)

    # Add the key(s) you want to set
    span.set_data("cache.key", [key])

    # Add the size of the value you stored in the cache
    span.set_data("cache.item_size", len(value))  # Warning: if value is very big this could use lots of memory

如果您使用的缓存不支持上述自动检测,可以使用以下自定义检测说明来发出缓存 Span:

  1. 使用您正在使用的缓存库获取缓存值。
  2. 使用 with sentry_sdk.start_span(...) 包装应用程序中使用缓存值的部分。
  3. op 设置为 cache.get
  4. cache.hit 设置为一个布尔值,表示是否成功从缓存中获取了值。
  5. cache.item_size 设置为一个表示缓存项大小的整数。

(上述步骤在代码片段中有详细说明。)

Copied
import my_caching
import sentry_sdk

key = "myCacheKey123"
value = None

with sentry_sdk.start_span(op="cache.get") as span:
    # Get a key from your caching solution
    value = my_caching.get(key)

    # Describe the cache server you are accessing
    span.set_data("network.peer.address", "cache.example.com/supercache")
    span.set_data("network.peer.port", 9000)

    # Add the key(s) you just retrieved from the cache
    span.set_data("cache.key", [key])

    if value is not None:
        # If you retrieved a value, the cache was hit
        span.set_data("cache.hit", True)

        # Optionally also add the size of the value you retrieved
        span.set_data("cache.item_size", len(value))
    else:
        # If you could not retrieve a value, it was a miss
        span.set_data("cache.hit", False)

您现在应该已经正确地添加了所需的 Span。请前往缓存仪表板查看缓存的性能。