简体   繁体   English

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

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

I'm new in nodejs, I'm using fastify and I want to be able to use the req.logger in all the classes functions of the flow, this because I have a the request-id on req.logger, the first solution that came to my mind is to pass as a parameter the logger through all the function/classes but I think that would make the code kind of dirty, here is an example of my code:我是 nodejs 的新手,我正在使用 fastify,我希望能够在流程的所有类函数中使用 req.logger,这是因为我在 req.logger 上有一个 request-id,这是第一个解决方案我想到的是将记录器作为参数传递给所有函数/类,但我认为这会使代码有点脏,这是我的代码示例:

app.ts应用程序.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 };

routes.ts路线.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 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

  }
}

Hope I have been clear.希望我已经清楚了。 Thanks!谢谢!

This may not be the best or only way to do it, but this has worked for me in the past.这可能不是最好的或唯一的方法,但这在过去对我有用。

Typically I structure my projects with an app.ts that just instantiates my FastifyInstance and then exports the log from that created instance.通常,我使用 app.ts 来构建我的项目,该 app.ts 只是实例化我的FastifyInstance ,然后从创建的实例中导出log This allows me to use the log where ever I want to.这使我可以在任何我想使用的地方使用日志。

It looks something like this.它看起来像这样。

app.ts应用程序.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.

server.ts服务器.ts

import app from './app';

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

app.listen({ ... });

Now I can use the logger outside of fastify stuff.现在我可以在 fastify 之外使用记录器了。

get-object-use-case.ts获取对象用例.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.
  }
}

This even allows you to log before your FastifyInstance is started.这甚至允许你在FastifyInstance启动之前登录。 Check out this codesandbox for a running example.查看此代码框以获取运行示例。

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

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