您应该如何在 TypeScript 中为 Morgan 创建 Winston 记录器流

How are you supposed to create Winston logger stream for Morgan in TypeScript

在 TypeScript 中创建将记录 express Morgan 中间件日志记录的 winston 记录器的正确方法是什么?我找到了一些 JavaScript 示例,但在将它们转换为 TypeScript 时遇到了问题,因为我收到错误 Type '{ write: (message: string, encoding: any) => {}; logger: any; }' is not assignable to type '(options?: any) => ReadableStream'. Object literal may only specify known properties, and 'write' does not exist in type '(options?: any) => ReadableStream'.

这是我的代码:

import { Logger, transports } from 'winston';

// http://tostring.it/2014/06/23/advanced-logging-with-nodejs/
// https://www.loggly.com/ultimate-guide/node-logging-basics/

const logger = new Logger({
    transports: [
        new (transports.Console)({
            level: process.env.NODE_ENV === 'production' ? 'error' : 'debug',
            handleExceptions: true,
            json: false,
            colorize: true
        }),
        new (transports.File)({
            filename: 'debug.log', level: 'info',
            handleExceptions: true,
            json: true,
            colorize: false
        })
    ],
    exitOnError: false,
});



if (process.env.NODE_ENV !== 'production') {
    logger.debug('Logging initialized at debug level');
}



// [ts]
// Type '{ write: (message: string, encoding: any) => {}; logger: any; }' is not assignable to type '(options?: any) => ReadableStream'.
//   Object literal may only specify known properties, and 'write' does not exist in type '(options?: any) => ReadableStream'.
logger.stream = {
    write: function (message: string, encoding: any) {
        logger.info(message);
    };
}


export default logger;

我已经能够通过调整我的代码以使用 const winston = require('winston'); 来解决这个问题,但想知道您应该如何维护类型?

stream 应该是 returns 流的工厂函数,而不是流本身。

流应该是真正的可读流,而不是模仿它的对象。

因为它应该也是可写的,所以它应该是双工的:

logger.stream = (options?: any) => new stream.Duplex({
    write: function (message: string, encoding: any) {
        logger.info(message);
    }
});

这是 Winston TS 类型建议的解决方案。我无法确认它是否正常工作。

感谢@estus 让我摆脱了挂断的状态。这是我最终使用的解决方案:

import { Logger, transports } from 'winston';
import stream from 'stream';
import split from 'split';

// http://tostring.it/2014/06/23/advanced-logging-with-nodejs/
// https://www.loggly.com/ultimate-guide/node-logging-basics/

const logger = new Logger({
    transports: [
        new (transports.Console)({
            level: process.env.NODE_ENV === 'production' ? 'error' : 'debug',
            handleExceptions: true,
            json: false,
            colorize: true
        }),
        new (transports.File)({
            filename: 'debug.log', level: 'info',
            handleExceptions: true,
            json: true,
            colorize: false
        })
    ],
    exitOnError: false,
});

if (process.env.NODE_ENV !== 'production') {
    logger.debug('Logging initialized at debug level');
}

logger.stream = split().on('data', function (message: string) {
    logger.info(message);
});

export default logger;

最终这个问题让我得到了最终的解决方案 - https://github.com/expressjs/morgan/issues/70

最终我把这个作为解决方案。我用一种叫做 write

的方法创建了一个 class
export class LoggerStream {
    write(message: string) {
        logger.info(message.substring(0, message.lastIndexOf('\n')));
    }
}

然后在添加到 express 时,我创建了一个 class:

的实例
 app.use(morgan('combined', { stream: new LoggerStream() }));

这很适合我的情况

如果您使用 TypeScript 类 作为记录器,您可以声明一个 stream() 函数,returns 来自 morgan 的 StreamOptions 类型:

import { StreamOptions } from 'morgan';

//...rest of the class code

public stream(): StreamOptions {
return {
  write: (message: string): void => {
    this.info(message.trim());
  }
};

然后你可以在 express 中间件中使用这个流函数:

app.use('combined', { stream: this.logger.stream()})