跳到主要内容

中间件示例:日志记录

以下示例记录 Prisma Client 查询运行所花费的时间

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

该示例基于以下示例 schema

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 Client 扩展来记录执行查询所花费的时间。一个功能示例可以在 这个 GitHub 仓库中找到。