指标
Prisma 客户端指标可让你详细了解 Prisma 客户端如何与数据库交互。你可以使用此见解来帮助诊断应用的性能问题。
¥Prisma Client metrics give you a detailed insight into how Prisma Client interacts with your database. You can use this insight to help diagnose performance issues with your application.
关于指标
¥About metrics
你可以以 JSON 或 Prometheus 格式导出指标并在控制台日志中查看它们,或者将它们集成到外部指标系统中,例如 StatsD 或 普罗米修斯。如果将它们集成到外部指标系统中,那么你可以查看一段时间内的指标数据。例如,你可以使用指标来帮助诊断应用的空闲和活动连接数如何变化。
¥You can export metrics in JSON or Prometheus formats and view them in a console log, or integrate them into an external metrics system, such as StatsD or Prometheus. If you integrate them into an external metrics system, then you can view the metrics data over time. For example, you can use metrics to help diagnose how your application's number of idle and active connections changes.
Prisma 客户端提供以下指标:
¥Prisma Client provides the following metrics:
-
计数器(始终增加):
¥Counters (always increase):
-
prisma_client_queries_total
:执行的 Prisma 客户端查询总数。¥
prisma_client_queries_total
: The total number of Prisma Client queries executed. -
prisma_datasource_queries_total
:执行的数据源查询总数(关系数据库中的 SQL 查询和 MongoDB 中的命令)。¥
prisma_datasource_queries_total
: The total number of datasource queries executed (SQL queries in relational databases, and commands in MongoDB).-
prisma_datasource_queries_total
返回的值可能大于prisma_client_queries_total
,因为某些 Prisma 客户端操作会创建多个查询。¥The value returned by
prisma_datasource_queries_total
can be greater thanprisma_client_queries_total
, because some Prisma Client operations create multiple queries.
-
-
prisma_pool_connections_closed_total
:关闭的池连接总数。¥
prisma_pool_connections_closed_total
: The total number of pool connections closed. -
prisma_pool_connections_opened_total
:当前打开的池连接数。¥
prisma_pool_connections_opened_total
: The number of currently open pool connections.
-
-
规范(可以增加或减少):
¥Gauges (can increase or decrease):
-
prisma_client_queries_active
:当前活动的 Prisma 客户端查询数量。¥
prisma_client_queries_active
: The number of currently active Prisma Client queries. -
prisma_client_queries_wait
:当前等待连接的 Prisma 客户端查询数量,因为所有连接都在使用中。¥
prisma_client_queries_wait
: The number of Prisma Client queries currently waiting for a connection because all connections are in use. -
prisma_pool_connections_busy
:当前繁忙的池连接数。这些池连接当前正在执行数据源查询。¥
prisma_pool_connections_busy
: The number of currently busy pool connections. These pool connections are currently executing a datasource query. -
prisma_pool_connections_idle
:当前未使用的池连接数。这些池连接正在等待下一个数据源查询运行。¥
prisma_pool_connections_idle
: The number of pool connections that are not currently being used. These pool connections are waiting for the next datasource query to run. -
prisma_pool_connections_open
:池连接 开放数量。¥
prisma_pool_connections_open
: The number of pool connections open.
-
-
直方图(指标数据分为值的集合;我们将集合中的每个容器称为 "bucket"):
¥Histograms (metrics data divided into a collection of values; we call each container in the collection a "bucket"):
-
prisma_client_queries_wait_histogram_ms
:所有 Prisma 客户端查询等待池连接的时间(以毫秒为单位)。¥
prisma_client_queries_wait_histogram_ms
: The time waiting for a pool connection for all Prisma Client queries in ms. -
prisma_client_queries_duration_histogram_ms
:所有执行的 Prisma 客户端查询的执行时间(以毫秒为单位)。这包括执行所有数据库查询以及执行所有数据库引擎活动(例如连接数据和将数据转换为正确格式)所需的时间。¥
prisma_client_queries_duration_histogram_ms
: The execution time for all executed Prisma Client queries in ms. This includes the time taken to execute all database queries, and to carry out all database engine activities, such as joining data and transforming data to the correct format. -
prisma_datasource_queries_duration_histogram_ms
:所有执行的数据源查询的执行时间(以毫秒为单位)。¥
prisma_datasource_queries_duration_histogram_ms
: The execution time for all executed Datasource queries in ms.
-
你可以 将全局标签添加到你的指标数据中 帮助你对指标进行分组和分离,例如按基础设施区域或服务器。
¥You can add global labels to your metrics data to help you group and separate your metrics, for example by infrastructure region or server.
先决条件
¥Prerequisites
要使用 Prisma 客户端指标,你必须执行以下操作:
¥To use Prisma Client metrics, you must do the following:
1. 安装最新的 Prisma ORM 依赖
¥ Install up-to-date Prisma ORM dependencies
使用 prisma
和 @prisma/client
npm 包的 3.15.0
或更高版本。
¥Use version 3.15.0
or higher of the prisma
and @prisma/client
npm packages.
npm install prisma@latest --save-dev
npm install @prisma/client@latest
2. 启用 Prisma 架构文件中的功能标志
¥ Enable the feature flag in the Prisma schema file
在 schema.prisma
文件的 generator
块中,启用 metrics
功能标志:
¥In the generator
block of your schema.prisma
file, enable the metrics
feature flag:
generator client {
provider = "prisma-client-js"
previewFeatures = ["metrics"]
}
检索 JSON 格式的指标
¥Retrieve metrics in JSON format
当你检索 JSON 格式的指标时,你可以按照返回的格式使用它们,或者使用 将它们发送至 StatSD 来可视化它们随时间的变化情况。
¥When you retrieve metrics in JSON format, you can use them in the format they are returned, or send them to StatSD to visualize how they change over time.
要检索 JSON 格式的指标,请将以下行添加到你的应用代码中:
¥To retrieve metrics in JSON format, add the following lines to your application code:
const metrics = await prisma.$metrics.json()
console.log(metrics)
这将返回指标如下:
¥This returns metrics as follows:
{
"counters": [
{
"key": "prisma_client_queries_total",
"labels": {},
"value": 0,
"description": "Total number of Prisma Client queries executed"
},
{
"key": "prisma_datasource_queries_total",
"labels": {},
"value": 0,
"description": "Total number of Datasource Queries executed"
},
{
"key": "prisma_pool_connections_closed_total",
"labels": {},
"value": 0,
"description": "Total number of Pool Connections closed"
},
{
"key": "prisma_pool_connections_opened_total",
"labels": {},
"value": 1,
"description": "Total number of Pool Connections opened"
}
...
],
"gauges": [
...
],
"histograms": [
...
]
}
Expand to view the full output
{
"counters": [
{
"key": "prisma_client_queries_total",
"labels": {},
"value": 2,
"description": "Total number of Prisma Client queries executed"
},
{
"key": "prisma_datasource_queries_total",
"labels": {},
"value": 5,
"description": "Total number of Datasource Queries executed"
},
{
"key": "prisma_pool_connections_open",
"labels": {},
"value": 1,
"description": "Number of currently open Pool Connections"
}
],
"gauges": [
{
"key": "prisma_client_queries_active",
"labels": {},
"value": 0,
"description": "Number of currently active Prisma Client queries"
},
{
"key": "prisma_client_queries_wait",
"labels": {},
"value": 0,
"description": "Number of Prisma Client queries currently waiting for a connection"
},
{
"key": "prisma_pool_connections_busy",
"labels": {},
"value": 0,
"description": "Number of currently busy Pool Connections (executing a datasource query)"
},
{
"key": "prisma_pool_connections_idle",
"labels": {},
"value": 21,
"description": "Number of currently unused Pool Connections (waiting for the next datasource query to run)"
},
{
"key": "prisma_pool_connections_open",
"labels": {},
"value": 1,
"description": "Number of currently open Pool Connections"
}
],
"histograms": [
{
"key": "prisma_client_queries_duration_histogram_ms",
"labels": {},
"value": {
"buckets": [
[0, 0],
[1, 0],
[5, 0],
[10, 1],
[50, 1],
[100, 0],
[500, 0],
[1000, 0],
[5000, 0],
[50000, 0]
],
"sum": 47.430541000000005,
"count": 2
},
"description": "Histogram of the duration of all executed Prisma Client queries in ms"
},
{
"key": "prisma_client_queries_wait_histogram_ms",
"labels": {},
"value": {
"buckets": [
[0, 0],
[1, 3],
[5, 0],
[10, 0],
[50, 0],
[100, 0],
[500, 0],
[1000, 0],
[5000, 0],
[50000, 0]
],
"sum": 0.0015830000000000002,
"count": 3
},
"description": "Histogram of the wait time of all Prisma Client Queries in ms"
},
{
"key": "prisma_datasource_queries_duration_histogram_ms",
"labels": {},
"value": {
"buckets": [
[0, 0],
[1, 0],
[5, 2],
[10, 2],
[50, 1],
[100, 0],
[500, 0],
[1000, 0],
[5000, 0],
[50000, 0]
],
"sum": 47.134498,
"count": 5
},
"description": "Histogram of the duration of all executed Datasource Queries in ms"
}
]
}
JSON 数据中的直方图
¥Histograms in JSON data
每个直方图 "bucket" 有两个值。第一个是桶的上限,第二个是计数(落入该桶的数据值的数量)。在以下示例中,有两个值在 11 到 20 之间的实例,以及五个值在 21 到 30 之间的实例:
¥Each histogram "bucket" has two values. The first one is the upper bound of the bucket, and the second one is the count (the number of data values that fall into that bucket). In the following example, there are two instances of values between 11 and 20, and five instances of values between 21 and 30:
...
[20, 2],
[30, 5],
...
将 Prisma 客户端指标与 StatsD 结合使用
¥Use Prisma Client metrics with StatsD
你可以将 JSON 格式的指标发送到 StatsD,以随时间推移可视化你的指标数据。
¥You can send JSON-formatted metrics to StatsD to visualize your metrics data over time.
注意:你必须将计数器指标作为一系列值提供给 StatsD,这些值是根据之前检索的指标而递增或递减的。但是,Prisma 客户端的计数器指标返回绝对值。因此,你必须将计数器指标转换为一系列递增和递减的值,并将它们作为仪表数据发送到 StatsD。在下面的代码示例中,我们将计数器指标转换为 diffHistograms
中递增和递减的仪表数据。
¥Note: You must provide counter metrics to StatsD as a series of values that are incremented or decremented from a previous retrieval of the metrics. However, Prisma Client's counter
metrics return absolute values. Therefore, you must convert your counter metrics to a series of incremented and decremented values and send them to StatsD as gauge data. In the code example below, we convert counter metrics into incremented and decremented gauge data in diffHistograms
.
在以下示例中,我们每 10 秒向 StatsD 发送一次指标。此时间与 StatsD 默认的 10 秒刷新率一致。
¥In the following example, we send metrics to StatsD every 10 seconds. This timing aligns with the default 10s flush rate of StatsD.
import StatsD from 'hot-shots'
let statsd = new StatsD({
port: 8125,
})
const diffMetrics = (metrics: Metric<MetricHistogram>[]) => {
return metrics.map((metric) => {
let prev = 0;
const diffBuckets = metric.value.buckets.map<MetricHistogramBucket>(
(values) => {
const [bucket, value] = values
const diff = value - prev
prev = value
return [bucket, diff]
}
)
metric.value.buckets = diffBuckets
return metric
})
}
let previousHistograms: Metric<MetricHistogram>[] = []
const statsdSender = async () => {
const metrics = await prisma.$metrics.json()
metrics.counters.forEach((counter: any) => {
statsd.gauge('prisma.' + counter.key, counter.value, (...res) => {})
});
metrics.gauges.forEach((counter: any) => {
statsd.gauge('prisma.' + counter.key, counter.value, (...res) => {})
})
if (!previousHistograms.length) {
previousHistograms = diffMetrics(metrics.histograms)
return
}
const diffHistograms = diffMetrics(metrics.histograms);
diffHistograms.forEach((diffHistogram, histogramIndex) => {
diffHistogram.value.buckets.forEach((values, bucketIndex) => {
const [bucket, count] = values
const [_, prev] =
previousHistograms[histogramIndex].value.buckets[bucketIndex]
const change = count - prev
for (let sendTimes = 0; sendTimes < change; sendTimes++) {
statsd.timing('prisma.' + diffHistograms.key, bucket)
}
})
})
previousHistograms = diffHistograms
}
setInterval(async () => await statsdSender(), 10000)
以 Prometheus 格式检索指标
¥Retrieve metrics in Prometheus format
当你以 Prometheus 格式检索 Prisma 客户端指标时,你可以按照返回的格式使用它们,或者使用 将它们发送到 Prometheus 指标系统 来可视化它们随时间的变化情况。
¥When you retrieve Prisma Client metrics in Prometheus format, you can use them in the format they are returned, or send them to the Prometheus metrics system to visualize how they change over time.
要检索 Prometheus 格式的指标,请将以下行添加到你的应用代码中:
¥To retrieve metrics in Prometheus format, add the following lines to your application code:
const metrics = await prisma.$metrics.prometheus()
console.log(metrics)
这将返回指标如下:
¥This returns metrics as follows:
# HELP prisma_client_queries_total Total number of Prisma Client queries executed
# TYPE prisma_client_queries_total counter
prisma_client_queries_total 14
...
# HELP prisma_pool_connections_busy The number of active connections in use.
# TYPE prisma_pool_connections_busy gauge
prisma_pool_connections_busy 0
...
# HELP prisma_client_queries_wait_histogram_ms The wait time for a worker to get a connection.
# TYPE prisma_client_queries_wait_histogram_ms histogram
prisma_client_queries_wait_histogram_ms_bucket{le="0"} 0
prisma_client_queries_wait_histogram_ms_bucket{le="1"} 3
Expand to view the full output
# HELP query_total_operations
# TYPE query_total_operations counter
query_total_operations 2
# HELP prisma_datasource_queries_total
# TYPE prisma_datasource_queries_total counter
prisma_datasource_queries_total 28
# HELP prisma_pool_connections_closed_total Total number of Pool Connections closed
# TYPE prisma_pool_connections_closed_total counter
prisma_pool_connections_closed_total 0
# HELP prisma_pool_connections_opened_total Total number of Pool Connections opened
# TYPE prisma_pool_connections_opened_total counter
prisma_pool_connections_opened_total 0
# HELP prisma_client_queries_active Number of currently active Prisma Client queries
# TYPE prisma_client_queries_active gauge
prisma_client_queries_active 0
# HELP prisma_client_queries_wait Number of queries currently waiting for a connection
# TYPE prisma_client_queries_wait gauge
prisma_client_queries_wait 0
# HELP prisma_pool_connections_busy Number of currently busy Pool Connections (executing a datasource query)
# TYPE prisma_pool_connections_busy gauge
prisma_pool_connections_busy 0
# HELP prisma_pool_connections_idle Number of currently unused Pool Connections (waiting for the next pool query to run)
# TYPE prisma_pool_connections_idle gauge
prisma_pool_connections_idle 21
# HELP prisma_pool_connections_open Number of currently open Pool Connections
# TYPE prisma_pool_connections_open gauge
prisma_pool_connections_open 1
# HELP prisma_pool_connections_open Number of currently open Pool Connections (able to execute a datasource query)
# TYPE prisma_pool_connections_open gauge
prisma_pool_connections_open 0
# HELP prisma_client_queries_wait_histogram_ms The wait time for a worker to get a connection.
# TYPE prisma_client_queries_wait_histogram_ms histogram
prisma_client_queries_wait_histogram_ms_bucket{le="0"} 0
prisma_client_queries_wait_histogram_ms_bucket{le="1"} 3
prisma_client_queries_wait_histogram_ms_bucket{le="5"} 3
prisma_client_queries_wait_histogram_ms_bucket{le="10"} 3
prisma_client_queries_wait_histogram_ms_bucket{le="50"} 3
prisma_client_queries_wait_histogram_ms_bucket{le="100"} 3
prisma_client_queries_wait_histogram_ms_bucket{le="500"} 3
prisma_client_queries_wait_histogram_ms_bucket{le="1000"} 3
prisma_client_queries_wait_histogram_ms_bucket{le="5000"} 3
prisma_client_queries_wait_histogram_ms_bucket{le="50000"} 3
prisma_client_queries_wait_histogram_ms_bucket{le="+Inf"} 3
prisma_client_queries_wait_histogram_ms_sum 0.023208
prisma_client_queries_wait_histogram_ms_count 3
# HELP prisma_client_queries_duration_histogram_ms Histogram of the duration of all executed Prisma Client queries in ms
# TYPE prisma_client_queries_duration_histogram_ms histogram
prisma_client_queries_duration_histogram_ms_bucket{le="0"} 0
prisma_client_queries_duration_histogram_ms_bucket{le="1"} 1
prisma_client_queries_duration_histogram_ms_bucket{le="5"} 2
prisma_client_queries_duration_histogram_ms_bucket{le="10"} 2
prisma_client_queries_duration_histogram_ms_bucket{le="50"} 2
prisma_client_queries_duration_histogram_ms_bucket{le="100"} 2
prisma_client_queries_duration_histogram_ms_bucket{le="500"} 2
prisma_client_queries_duration_histogram_ms_bucket{le="1000"} 2
prisma_client_queries_duration_histogram_ms_bucket{le="5000"} 2
prisma_client_queries_duration_histogram_ms_bucket{le="50000"} 2
prisma_client_queries_duration_histogram_ms_bucket{le="+Inf"} 2
prisma_client_queries_duration_histogram_ms_sum 3.197624
prisma_client_queries_duration_histogram_ms_count 2
# HELP prisma_datasource_queries_duration_histogram_ms Histogram of the duration of all executed Datasource Queries in ms
# TYPE prisma_datasource_queries_duration_histogram_ms histogram
prisma_datasource_queries_duration_histogram_ms_bucket{le="0"} 0
prisma_datasource_queries_duration_histogram_ms_bucket{le="1"} 5
prisma_datasource_queries_duration_histogram_ms_bucket{le="5"} 5
prisma_datasource_queries_duration_histogram_ms_bucket{le="10"} 5
prisma_datasource_queries_duration_histogram_ms_bucket{le="50"} 5
prisma_datasource_queries_duration_histogram_ms_bucket{le="100"} 5
prisma_datasource_queries_duration_histogram_ms_bucket{le="500"} 5
prisma_datasource_queries_duration_histogram_ms_bucket{le="1000"} 5
prisma_datasource_queries_duration_histogram_ms_bucket{le="5000"} 5
prisma_datasource_queries_duration_histogram_ms_bucket{le="50000"} 5
prisma_datasource_queries_duration_histogram_ms_bucket{le="+Inf"} 5
prisma_datasource_queries_duration_histogram_ms_sum 1.8407059999999997
prisma_datasource_queries_duration_histogram_ms_count 5
histogram
类型的指标以 Prometheus 格式公开三种不同类别的值:
¥Metrics of type histogram
expose three different class of values in the Prometheus format:
-
观察桶的多个累积计数器。这些计数器带有
_bucket{le="<upper inclusive bound>"}
后缀。例如,prisma_datasource_queries_duration_histogram_ms
有一个计数器暴露为prisma_datasource_queries_duration_histogram_ms_bucket{le="1"}
¥Multiple cumulative counters for observation buckets. These counters are suffixed with
_bucket{le="<upper inclusive bound>"}
. For example,prisma_datasource_queries_duration_histogram_ms
has a counter exposed asprisma_datasource_queries_duration_histogram_ms_bucket{le="1"}
当观察到的值小于或等于存储桶的上限时,Prisma 客户端指标会将该存储桶增加 1。假设你有包含上限分别为 0、1、5、10 和 50 的存储桶。如果观察到的值为 5,则 Prisma 客户端指标会从第三个存储桶开始递增,因为该值大于 0 且大于 1,但小于或等于 5、10 和 50。
¥When an observed value is less than or equal to the upper inclusive bound of a bucket, then Prisma Client metrics increments that bucket by 1. Suppose that you have buckets with the upper inclusive bounds 0, 1, 5, 10, and 50 respectively. If the observed value is 5 then Prisma Client metrics increments the third bucket onwards, because the value is greater than 0 and greater than 1, but less than or equal to 5, 10, and 50.
-
所有观测值的单个总和。该计数器的后缀为
_sum
。例如prisma_datasource_queries_duration_histogram_ms
的总和被暴露为prisma_datasource_queries_duration_histogram_ms_sum
。¥A single total sum for all observed values. This counter is suffixed with
_sum
. For example the total sum ofprisma_datasource_queries_duration_histogram_ms
is exposed asprisma_datasource_queries_duration_histogram_ms_sum
. -
已观察到的事件数的计数。该计数器的后缀为
_count
。例如,prisma_datasource_queries_duration_histogram_ms
事件的总数显示为prisma_datasource_queries_duration_histogram_ms_count
。¥The count of the number of events that have been observed. This counter is suffixed with
_count
. For example the total count ofprisma_datasource_queries_duration_histogram_ms
events is exposed asprisma_datasource_queries_duration_histogram_ms_count
.
有关更多信息,请阅读 指标类型 上的 Prometheus 文档。
¥For more information, read the Prometheus documentation on metric types.
将 Prisma Client 指标与 Prometheus 指标系统结合使用
¥Use Prisma Client metrics with the Prometheus metrics system
在大多数情况下,Prometheus 必须抓取端点才能检索指标。以下示例展示了如何使用 Express.js
发送数据:
¥In the majority of cases, Prometheus must scrape an endpoint to retrieve metrics. The following example shows how to send data with Express.js
:
import { PrismaClient } from '@prisma/client'
import express, { Request, Response } from 'express'
const app = express()
const port = 4000
const prisma = new PrismaClient()
app.get('/metrics', async (_req, res: Response) => {
const metrics = await prisma.$metrics.prometheus()
res.end(metrics)
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
以下示例展示了如何将 Prisma 客户端指标与其他 Prometheus 客户端库相结合,这些客户端库也与 Express.js
一起使用 REST API 端点提供服务:
¥The following example shows how to combine Prisma Client metrics with other Prometheus client libraries that are also served with a REST API endpoint in conjunction with Express.js
:
import { PrismaClient } from '@prisma/client'
import express, { Request, Response } from 'express'
import prom from 'prom-client'
const app = express()
const port = 4000
const prisma = new PrismaClient()
const register = new prom.Registry()
prom.collectDefaultMetrics({ register })
app.get('/metrics', async (_req, res: Response) => {
const prismaMetrics = await prisma.$metrics.prometheus()
const appMetrics = await register.metrics()
res.end(prismaMetrics + appMetrics)
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
全局标签
¥Global labels
你可以向指标添加全局标签,以帮助你对指标进行分组和分离。Prisma Client 的每个实例都会将这些标签添加到它生成的指标中。例如,你可以按基础设施区域或服务器对指标进行分组,并使用 { server: us_server1', 'app_version': 'one' }
等标签。
¥You can add global labels to your metrics to help you group and separate your metrics. Each instance of Prisma Client adds these labels to the metrics that it generates. For example, you can group your metrics by infrastructure region, or by server, with a label like { server: us_server1', 'app_version': 'one' }
.
全局标签使用 JSON 和 Prometheus 格式的指标。
¥Global labels work with JSON and Prometheus-formatted metrics.
例如,要将全局标签添加到 JSON 格式的指标,请将以下代码添加到你的应用中:
¥For example, to add global labels to JSON-format metrics, add the following code to your application:
const metrics = prisma.$metrics.json({
globalLabels: { server: 'us_server1', app_version: 'one' },
})
console.log(metrics)
这将返回以下格式的信息:
¥This returns information in the following format:
{
"counters": [
{
"key": "query_total_operations",
"labels": { "server": "us_server1", "app_version": "one" },
"value": 0,
"description": "The total number of operations executed"
},
{
"key": "prisma_datasource_queries_total",
"labels": { "server": "us_server1", "app_version": "one" },
"value": 0,
"description": "The total number of queries executed"
},
...
],
"gauges": [
...
],
"histograms": [
...
]
}