如何将Winston与Typeorm结合使用?

时间:2019-07-11 11:42:33

标签: node.js winston typeorm

我希望所有操作都被写入日志文件。但这不会发生,文件本身是创建的,但始终为空。

如何解决?还是我做错了什么?

looger.ts:

import { LoggerOptions, createLogger, transports } from 'winston';

export const logger = createLogger(<LoggerOptions> {
    exitOnError: false,
    transports: [
        new transports.Console({
            level: 'debug'
        }),
        new transports.File({
            filename: './logs/errors.log',
            level: 'debug',
            maxsize: 1024 * 1024 * 10
        }),
        new transports.File({
            filename: './logs/logger.log',
            level: 'log'
        })
    ], exceptionHandlers: [
        new transports.File({
            filename: './logs/exceptions.log',
            level: 'debug',
            maxsize: 1024 * 1024 * 10
        })
    ]
});

server.ts:

import * as express from 'express'
import { Request, Response, NextFunction } from 'express';
import { logger } from './utils/logger';

class Server {
  public express;

  constructor () {
    this.express = express()
    this.log()
  }

  private log(): void {
    this.express.use((err: Error,  req: Request, res: Response, next: NextFunction) => {
        logger.error(err.stack);
        logger.log(res.stack);
    });
  }
}
export default new Server().express;

1 个答案:

答案 0 :(得分:0)

您必须定义自己的Logger实现,然后在其中调用Winston API。

import { Logger, QueryRunner } from "typeorm";

export class TypeOrmLogger implements Logger {

    log(level: "log" | "info" | "warn", message: any, queryRunner?: QueryRunner): any {
        ...
    }

    logMigration(message: string, queryRunner?: QueryRunner): any {
        ...
    }

    logQuery(query: string, parameters?: any[], queryRunner?: QueryRunner): any {
        ...
    }

    logQueryError(error: string, query: string, parameters?: any[], queryRunner?: QueryRunner): any {
        ...
    }

    logQuerySlow(time: number, query: string, parameters?: any[], queryRunner?: QueryRunner): any {
        const pinoLogger = logger.spawnPino("SQLSlow");
        pinoLogger.warn(query, {time, ...parameters});
    }

    logSchemaBuild(message: string, queryRunner?: QueryRunner): any {
        ...
    }
}

然后,在连接选项中将TypeOrmLogger定义为记录器。