Skip to main content

记录

使用 PrismaClient log 参数配置 日志级别 ,包括警告、错误以及有关发送到数据库的查询的信息。

¥Use the PrismaClient log parameter to configure log levels , including warnings, errors, and information about the queries sent to the database.

Prisma 客户端支持两种类型的日志记录:

¥Prisma Client supports two types of logging:

info

你还可以使用 DEBUG 环境变量在 Prisma Client 中启用调试输出。请参阅 调试 了解更多信息。

¥You can also use the DEBUG environment variable to enable debugging output in Prisma Client. See Debugging for more information.

info

如果你想详细了解 Prisma 客户端在单个操作级别的性能,请参阅 追踪

¥If you want a detailed insight into your Prisma Client's performance at the level of individual operations, see Tracing.

记录到标准输出

¥Log to stdout

将所有日志级别打印到 stdout 的最简单方法是传入数组 LogLevel 对象:

¥The simplest way to print all log levels to stdout is to pass in an array LogLevel objects:

const prisma = new PrismaClient({
log: ['query', 'info', 'warn', 'error'],
})

这是传入 LogDefinition 对象数组的简短形式,其中 emit 的值始终为 stdout

¥This is the short form of passing in an array of LogDefinition objects where the value of emit is always stdout:

const prisma = new PrismaClient({
log: [
{
emit: 'stdout',
level: 'query',
},
{
emit: 'stdout',
level: 'error',
},
{
emit: 'stdout',
level: 'info',
},
{
emit: 'stdout',
level: 'warn',
},
],
})

基于事件的日志记录

¥Event-based logging

要使用基于事件的日志记录:

¥To use event-based logging:

  1. 对于特定的日志级别,例如查询,设置 emitevent

    ¥Set emit to event for a specific log level, such as query

  2. 使用 $on() 方法订阅事件

    ¥Use the $on() method to subscribe to the event

以下示例订阅所有 query 事件并将 durationquery 写入控制台:

¥The following example subscribes to all query events and write the duration and query to console:

const prisma = new PrismaClient({
log: [
{
emit: 'event',
level: 'query',
},
{
emit: 'stdout',
level: 'error',
},
{
emit: 'stdout',
level: 'info',
},
{
emit: 'stdout',
level: 'warn',
},
],
})

prisma.$on('query', (e) => {
console.log('Query: ' + e.query)
console.log('Params: ' + e.params)
console.log('Duration: ' + e.duration + 'ms')
})
Show CLI results
Query: SELECT "public"."User"."id", "public"."User"."email", "public"."User"."name" FROM "public"."User" WHERE 1=1 OFFSET $1
Params: [0]
Duration: 3ms
Query: SELECT "public"."Post"."id", "public"."Post"."title", "public"."Post"."authorId" FROM "public"."Post" WHERE "public"."Post"."authorId" IN ($1,$2,$3,$4) OFFSET $5
Params: [2, 7, 18, 29]
Duration: 2ms

确切的 事件 (e) 类型和可用属性 取决于日志级别。

¥The exact event (e) type and the properties available depends on the log level.