如何使用 Sequelize 记录相关 id?

问题描述 投票:0回答:1

我的 REST API 服务器包含用户实体的 CRUD 端点,该实体使用 Sequelize 保存到数据库中。每个端点都会生成一个 uuid v4 相关 ID,该 ID 应该出现在每个日志消息中。我使用 pino 和子记录器,并提供相关 id 作为绑定选项,因此开发人员不必担心甚至不知道任何相关 id,也不需要在每个日志消息中提供它(开发人员只需使用记录器在特定上下文(其余端点处理程序))。

有没有办法将相关 ID 或子记录器注入 Sequelize 中,以在不同上下文(其余端点处理程序)中记录具有不同相关 ID 的 Sequelize 查询?

我不想在每个 Sequelize 模型操作中提供记录器 fn (不实用/繁琐/容易出错)。

我想实现这样的目标:

1. rest handler is called // this is the start of the execution context
2. correlation id CID is generated and injected into logger and ???somehow into Sequelize??? // CID is constant from the perspective of the current execution context
3. some business logic // logs every log message with CID without explicitly specifying it
4. await User.findByPK(id) // I do not want to pass CID in here as it should be clear from the execution context
5. a log message is produced containing CID
6. some business logic // logs every log message with CID without explicitly specifying it
7. rest handler finished // end of the execution context

注意:“注入记录器”是指使用绑定选项创建子记录器,以确保日志记录属性不会混淆。

logging sequelize.js correlation
1个回答
0
投票

您可以在每个 sequalize 命令中附加日志记录功能,例如:

查询:

 const corellationId = req.headers["x-correlation-id"];
 const myData = await myRepository.findOne({
    attributes: ["id", "name"],
    where: { id },
    logging: (message) => logger.log({ message, corellationId }),
  });

插入:

const corellationId = req.headers["x-correlation-id"];
await myRepository.create({
    id: uuidv4(),
    ...data,
  }, 
  {
    logging: (message) => logger.log({ message, corellationId }),
  });
© www.soinside.com 2019 - 2024. All rights reserved.