【问题标题】:How to add morgan to Loopback 4 RestApplication?如何将摩根添加到 Loopback 4 RestApplication?
【发布时间】:2021-01-10 02:36:48
【问题描述】:

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

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

   if (finished) {
     return;
   }

   await super.handle(context);
 }
}
  1. this.sequence(MySequence) 文件中调用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",

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

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

【问题讨论】:

    标签: loopbackjs loopback4


    【解决方案1】:

    我使用了 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',
        });
    }
    

    【讨论】:

      【解决方案2】:

      请将您的更改恢复为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

      【讨论】:

      • 将更改还原为MySequence.ts 并按照示例我可以看到 morgan 在使用调试时已注册为中间件,但仍不会打印出 HTTP 调用。
      猜你喜欢
      • 1970-01-01
      • 2019-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多