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

JoA*_*MoS 6 node.js winston typescript morgan

在TypeScript中创建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;
Run Code Online (Sandbox Code Playgroud)

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

JoA*_*MoS 7

最终,我最终将此作为解决方案。我用一种叫做 write 的方法创建了一个类

export class LoggerStream {
    write(message: string) {
        logger.info(message.substring(0, message.lastIndexOf('\n')));
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在添加到 express 时我创建了一个类的实例:

 app.use(morgan('combined', { stream: new LoggerStream() }));
Run Code Online (Sandbox Code Playgroud)

这对我的情况很有效


Est*_*ask 5

stream 预计是返回流的工厂函数,而不是流本身。

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

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

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

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