首页 > 解决方案 > 你应该如何在 TypeScript 中为 Morgan 创建 Winston 记录器流

问题描述

在 TypeScript 中创建将记录快速 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');但想知道您应该如何维护类型?

标签: node.jstypescriptwinstonmorgan

解决方案


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

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

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

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

这很适合我的情况


推荐阅读