跳至主要内容

中间件示例:日志记录

以下示例记录了 Prisma 客户端查询运行所需的时间

const prisma = new PrismaClient()

prisma.$use(async (params, next) => {
const before = Date.now()

const result = await next(params)

const after = Date.now()

console.log(`Query ${params.model}.${params.action} took ${after - before}ms`)

return result
})

const create = await prisma.post.create({
data: {
title: 'Welcome to Prisma Day 2020',
},
})

const createAgain = await prisma.post.create({
data: {
title: 'All about database collation',
},
})

示例输出

Query Post.create took 92ms
Query Post.create took 15ms

该示例基于以下示例架构

generator client {
provider = "prisma-client-js"
}

datasource db {
provider = "mysql"
url = env("DATABASE_URL")
}

model Post {
authorId Int?
content String?
id Int @id @default(autoincrement())
published Boolean @default(false)
title String
user User? @relation(fields: [authorId], references: [id])
language String?

@@index([authorId], name: "authorId")
}

model User {
email String @unique
id Int @id @default(autoincrement())
name String?
posts Post[]
extendedProfile Json?
role Role @default(USER)
}

enum Role {
ADMIN
USER
MODERATOR
}

更进一步

您也可以使用 Prisma 客户端扩展 记录执行查询所需的时间。可以在 此 GitHub 存储库 中找到一个功能性示例。