如何将摩根添加到 Loopback 4 RestApplication?

How to add morgan to Loopback 4 RestApplication?

我只是想添加 morgan 来记录我的 http 调用。我试过的两种方法是:

  1. 将其添加到 MySequence class:
export class MySequence extends MiddlewareSequence {
 async handle(context: RequestContext) {
   const finished = await this.invokeMiddleware(context, [morgan()]);

   if (finished) {
     return;
   }

   await super.handle(context);
 }
}
  1. application.ts 文件中调用 this.sequence(MySequence) 之前添加它:
export class MyAppApiApplication extends BootMixin(
  ServiceMixin(RepositoryMixin(RestApplication)),
) {
  constructor(options: ApplicationConfig = {}) {
    super(options);

    this.expressMiddleware(
      morgan,
      {},
      {
        injectConfiguration: 'watch',
        key: 'middleware.morgan',
      }
    );
    this.sequence(MySequence);

    ...
}

第一种方法在我更新我的环回依赖项之前有效:

"@loopback/boot": "^2.4.1",
"@loopback/core": "^2.9.3",
"@loopback/repository": "^2.11.0",
"@loopback/rest": "^6.0.0",
"@loopback/rest-explorer": "^2.2.8",
"@loopback/service-proxy": "^2.3.6",

至:

"@loopback/boot": "^3.0.1",
"@loopback/core": "^2.10.1",
"@loopback/repository": "^3.0.1",
"@loopback/rest": "^7.0.1",
"@loopback/rest-explorer": "^3.0.1",
"@loopback/service-proxy": "^3.0.1",

更新显然做了一些使其停止工作的事情,但我不知道是什么。

此外,我在文档中看到了其他方法,例如使用拦截器的方法,但当它应该像向 Express 应用程序添加中间件一样简单时,感觉有点矫枉过正。

请将您的更改还原为 MySequence.ts。以下就足够了:

export class MySequence extends MiddlewareSequence {
}

您应该知道使用 this.expressMiddleware 注册的 morgan 中间件将被 MiddlewareSequence 自动发现。

查看工作示例:

https://github.com/strongloop/loopback-next/blob/master/examples/todo/src/application.ts#L46

我使用了 Raymond 的示例,但必须从配置对象中删除 stream.write 函数才能使其工作。按原样使用示例,我可以看到中间件正在注册,但仍然看不到 Morgan 的日志。

刚刚将 defaultConfig 对象留空:

private setupLogging() {
    const morganFactory = (config?: morgan.Options<Request, Response>) => {
      this.debug('Morgan configuration', config);
      return morgan('combined', config);
    };

    const defaultConfig: morgan.Options<Request, Response> = {};

    this.expressMiddleware(morganFactory, defaultConfig, {
      injectConfiguration: 'watch',
      key: 'middleware.morgan',
    });
}