繁体   English   中英

如何在其他类中使用 fastify 请求记录器而无需将其作为参数传递?

[英]How can I use fastify request logger in other classes without having to pass it as a parameter?

我是 nodejs 的新手,我正在使用 fastify,我希望能够在流程的所有类函数中使用 req.logger,这是因为我在 req.logger 上有一个 request-id,这是第一个解决方案我想到的是将记录器作为参数传递给所有函数/类,但我认为这会使代码有点脏,这是我的代码示例:

应用程序.ts

import pino from 'pino';
import fastify from 'fastify';

declare module 'fastify' {
  interface FastifyInstance {
    // augment fastify instance with the config object types
    config: Config;
  }
}

function build() {

  const app = fastify({
    logger: pino({
      name: process.env.NAME,
      level: process.env.LOG_LEVEL,
    }),
    disableRequestLogging: true,
    requestIdHeader: 'correlation-id',
    requestIdLogLabel: 'correlationId',
  });
  // register plugins 
  
  app.register(apiRoutes, fastify => ({
    getObjectUseCase: new GetObjectUseCase(
      new TestClass()),
  }));

  return app;
}
export { build };

路线.ts

import { FastifyPluginCallback } from 'fastify';
import { StatusCodes } from 'http-status-codes';

export const apiRoutes: FastifyPluginCallback<RoutesOpts> = async (fastify, options, done) => {
  const getObjectUseCase = options.getObjectUseCase; 

  fastify.get<object>('/v1/api/:id', async (req, reply) => {
    const id = req.params.payoutId;
    req.logger.info('This is a logger print'); // has the correlation id inside it while printing
    const storedObject = await getObjectCase.execute(id);
    reply.code(StatusCodes.OK).send(storedObject);
  });
}

GetObjectUseCase.ts

export class GetObjectUseCase {
  private anotherClass: TestClass;

  constructor(anotherClass: TestClass) {
    this. anotherClass = anotherClass;
  }

  async execute(id: string): Promise<StoredObject> {
    // I want to use the logger here with have the correlation id on it without having to pass it as an argument on the method, how is it posible?
    return this.anotherClass.getById(id);
    // also needed to use it inside anotherClass.getById so I will need to pass the logger also in the method

  }
}

希望我已经清楚了。 谢谢!

这可能不是最好的或唯一的方法,但这在过去对我有用。

通常,我使用 app.ts 来构建我的项目,该 app.ts 只是实例化我的FastifyInstance ,然后从创建的实例中导出log 这使我可以在任何我想使用的地方使用日志。

它看起来像这样。

应用程序.ts

import fastify from 'fastify';

const app = fastify({ logger: true /* Your logging configuration */});

export default app;
export const logger = app.log; // Allows me to log where ever I want.

服务器.ts

import app from './app';

... // All your fastify configuration and other stuff.

app.listen({ ... });

现在我可以在 fastify 之外使用记录器了。

获取对象用例.ts

import { logger } from './app'; // Import your fastify logger to use in this class.

export class GetObjectUseCase {
  private anotherClass: TestClass;

  constructor(anotherClass: TestClass) {
    this. anotherClass = anotherClass;
  }

  async execute(id: string): Promise<StoredObject> {
    logger.info({/* Whatever you want to log here. */}); // Now you can use the logger here.
    return this.anotherClass.getById(id); // You can just import the logger into the TestClass file to get logging enabled there.
  }
}

这甚至允许你在FastifyInstance启动之前登录。 查看此代码框以获取运行示例。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM