【问题标题】:Using Winston in typescript在打字稿中使用温斯顿
【发布时间】:2017-12-23 13:47:35
【问题描述】:

我不知道如何在 typescript 中使用日志记录模块 Winston。当我尝试设置记录器级别时出现错误,当我尝试记录错误时出现另一个错误:

import * as logger from "winston";

logger.level = 'debug';
// [ts] Cannot assign to 'level' because it is a constant or a read-only property.

logger.error(new Error('test'));
// [ts] Argument of type 'Error' is not assignable to parameter of type 'string'.

我已将winston@types/winston 添加到我的项目中。


编辑: 完成 Joshua 的回答,似乎默认情况下,winston 登录到...无处。您必须添加一个传输才能使其工作:

import * as logger from "winston";

logger.configure({
    level: 'debug',
    transports: [
        new logger.transports.Console({
            colorize: true
        })
    ]
});

【问题讨论】:

    标签: typescript winston


    【解决方案1】:

    以下是 Winston 的类型定义:

    https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/winston/index.d.ts

    如果您查看文件底部,默认导出声明为const,因此当您尝试修改level 属性时,它会向您抱怨,因为您正在尝试修改const 对象.以下是相关行:

    declare const winston: winston.Winston;
    export = winston;
    

    不要尝试直接设置该属性,而是尝试使用configure 方法(注意您的logger 导入类型为Winston

    logger.configure({
        level: 'verbose',
        ...
    })
    

    如果这不起作用(我不确定 configure 调用究竟需要什么),您可以尝试创建一个新的 LoggerInstance,您将能够对其进行修改。

    您的第二个错误是因为您传递了一个 Error 对象,而该对象应该是 string。 Winston.info 的声明在这里:

    info: LeveledLogMethod;
    

    这里是LeveledLogMethod接口:

    interface LeveledLogMethod {
        (msg: string, callback: LogCallback): LoggerInstance;
        (msg: string, meta: any, callback: LogCallback): LoggerInstance;
        (msg: string, ...meta: any[]): LoggerInstance;
    }
    

    【讨论】:

    • 这是否意味着不可能用 Winston 记录错误?这对我来说听起来很疯狂。
    • 你可以记录Errormessage属性。
    • 这实际上记录了错误:let err:any = new Error('test'); logger.error(err);我觉得 winston 的类型定义有问题。
    • 另一种可行的方法是使用接口中定义的第三种形式,即执行logger.error("test", new Error("test error");之类的操作,我认为类型定义不正确是正确的。我认为它还应该包括(...meta: any[]): LoggerInstance;,但我不确定语法到底是什么。查看源代码后,在我看来log 方法试图巧妙地处理它接收到的对象,例如Errors,而meta 参数表明了这一点。
    猜你喜欢
    • 2017-06-11
    • 2019-10-28
    • 1970-01-01
    • 2018-07-01
    • 2016-08-29
    • 1970-01-01
    • 2018-11-19
    • 2013-10-23
    • 2014-12-10
    相关资源
    最近更新 更多