【问题标题】:How to configure a winston service with nestjs?如何使用nestjs 配置winston 服务?
【发布时间】:2020-09-05 06:31:00
【问题描述】:

我有一个基本的 nestjs 应用程序,我正在尝试使用 winston 作为记录器服务...这会破坏我的应用程序,我真的不知道要修复/恢复它。 我已经尝试再次卸载winston包、rm node_modules和npm install,没有任何效果。

node -v: v11.15.
nest -v: 7.1.5
yarn -v: 1.22.4
npm -v: 6.14.5

我得到的错误:

[11:37:19 AM] Found 0 errors. Watching for file changes.

internal/modules/cjs/loader.js:670
    throw err;
    ^

Error: Cannot find module './app.module'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:668:15)
    at Function.Module._load (internal/modules/cjs/loader.js:591:27)
    at Module.require (internal/modules/cjs/loader.js:723:19)
    at require (internal/modules/cjs/helpers.js:14:16)
    at Object.<anonymous> (/Users/dtmirror/app-api/dist/src/main.js:4:22)
    at Module._compile (internal/modules/cjs/loader.js:816:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:827:10)
    at Module.load (internal/modules/cjs/loader.js:685:32)
    at Function.Module._load (internal/modules/cjs/loader.js:620:12)
    at Function.Module.runMain (internal/modules/cjs/loader.js:877:12)

安装包:

npm i winston

记录器服务:

import * as winston from 'winston';
import { LoggerOptions } from 'winston';

export class LoggerService {
    private logger;

    public static loggerOptions: LoggerOptions = {
        transports: [
            new winston.transports.File({ filename: 'app.log' })
        ]
    }

    constructor(private context: string, transport?) {
        this.logger = (winston as any).createLogger(LoggerService.loggerOptions);
    }

    log(message: string): void {
        const currentDate = new Date();
        this.logger.info(message, {
            timestamp: currentDate.toISOString(),
            context: this.context,
        })
    }
}

main.ts:

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { LoggerService } from '../logger.service'; // <-- this breaks everything

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  await app.listen(3000);
}
bootstrap();

我在这个阶段运行yarn start:dev 的那一刻,一切都崩溃了......

【问题讨论】:

  • 如果您删除该行,一切都会恢复吗?错误是在./app.module 找不到AppModule,所以看起来你的记录器与问题无关。
  • @Jay 不,如果我删除线,一切仍然坏...这是最困扰我的...
  • 那么你的记录器没有破坏任何东西。你能显示你的app.module 文件和srcdist 的目录结构吗?该错误似乎是通往AppModule 的错误路径
  • 老兄,非常感谢... logger.service.ts 在 src 目录之外... 我不得不删除软件包并重新安装它,将服务移到 src 文件夹中,现在一切都按预期工作。再次感谢您在 @JayMcDoniel 上花费的时间
  • 请在答案区添加解决方案,我可以给你一个大拇指!再次感谢

标签: javascript typescript logging nestjs winston


【解决方案1】:

对于AppModule 来说,这似乎是一个糟糕的导入。根据 cmets,logger 位于 src 目录之外,这最终导致 dist 呈现不同的形状

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-14
    • 2019-03-10
    • 2021-12-19
    • 2021-11-07
    • 2021-04-06
    • 1970-01-01
    • 2019-10-07
    • 1970-01-01
    相关资源
    最近更新 更多