Winston logging object

前端 未结 5 1965
轻奢々
轻奢々 2021-02-13 12:23

I use Winston for my backend logging I cannot log the object without using JSON.stringify which is annoying

logger.debug(`Register ${JSON.stringify(         


        
5条回答
  •  孤街浪徒
    2021-02-13 12:57

    I had to combine the solution provided by @SherloxFR and @Anton.

    const Winston = require('winston');
    const { format } = Winston;
    
    const options = {
        file: {
            ....
            format: format.combine(
                format.splat(), 
                format.json()
            ),
            ...
        },
        console: {
            ...
            format: format.combine(
                format.splat(),
                format.json()
            ),
            ...
        }
    };
    

    You can see that I added both format.splat() and format.json() to the options config in the above code.

    const logger = new Winston.createLogger({
        transports: [
            new Winston.transports.File(options.file),
            new Winston.transports.Console(options.console)
        ],
        exitOnError: false // do not exit on handled exceptions
    });
    

    That is how I used the options config object. You can actually write the format code inside the transports array but I don't like it that way. It's your choice anyway.

    After the configuration like that, the is how I used it in my code

    let myObj = {
       name: "StackOverflow",
    };
    
    logger.info('Content: %o', myObj);
    

    You can also spread it like this if you want

    logger.info('Content: %o', {...myObj});
    

    That's all. Winston should log your object with this set up.

提交回复
热议问题