Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Winston in typescript

I can't figure how to use the logging module Winston in typescript. I have an error when I try to set the logger level, and another one when I try to log an error:

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'.

I have added both winston and @types/winston to my project.


Edit: to complete Joshua answer, it seem that by default winston logs to... nowhere. You have to add a transport to make it work:

import * as logger from "winston";

logger.configure({
    level: 'debug',
    transports: [
        new logger.transports.Console({
            colorize: true
        })
    ]
});
like image 402
Christophe Le Besnerais Avatar asked Jul 18 '17 15:07

Christophe Le Besnerais


1 Answers

Here are the type definitions for Winston:

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

If you look at the bottom of the file, the default export is declared as const, so when you try to modify the level property, it complains at you because you are trying to modify a const object. Here are the relevant lines:

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

Instead of trying to set that property directly, try using the configure method (note that your logger import is of type Winston:

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

If this doesn't work (I'm not sure exactly what else the configure call expects), you might try creating a new LoggerInstance, which you will be able to modify.

Your second error is because you're passing an Error object where a string is expected. The declaration of Winston.info is here:

info: LeveledLogMethod;

And here is the LeveledLogMethod interface:

interface LeveledLogMethod {
    (msg: string, callback: LogCallback): LoggerInstance;
    (msg: string, meta: any, callback: LogCallback): LoggerInstance;
    (msg: string, ...meta: any[]): LoggerInstance;
}
like image 164
Joshua Breeden Avatar answered Sep 17 '22 18:09

Joshua Breeden