2017-07-18 51 views
3

我無法計算如何在打字稿中使用日誌記錄模塊Winston。我有一個錯誤,當我嘗試設置記錄水平,而另外一個,當我嘗試登錄的錯誤:在打字稿中使用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到我的項目。


編輯:完成約書亞的答案,它似乎在默認情況下溫斯頓記錄到...行不通的。你必須添加一個運輸,使其工作:

import * as logger from "winston"; 

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

回答

4

下面是類型定義爲溫斯頓:

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', 
    ... 
}) 

如果這不工作(我不確定配置調用期望的是什麼),你可以嘗試創建一個新的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; 
} 
+0

這是否意味着它是不可能記錄錯誤與溫斯頓?這聽起來對我來說很瘋狂。 –

+0

您可以記錄'Error'的'message'屬性。 –

+0

是的,但堆棧跟蹤將丟失 –