How can I add timestamp to logs using Node.js library Winston?

后端 未结 9 638
清歌不尽
清歌不尽 2021-01-31 12:55

I want to add timestamp to logs. What is the best way to achieve this?

9条回答
  •  爱一瞬间的悲伤
    2021-01-31 13:53

    Above answers did not work for me. In case you are trying to add timestamp to your logs using the latest version of Winston - 3.0.0-rc1, this worked like charm:

        const {transports, createLogger, format} = require('winston');
    
        const logger = createLogger({
            format: format.combine(
                format.timestamp(),
                format.json()
            ),
            transports: [
                new transports.Console(),
                new transports.File({filename: 'logs/error/error.log', level: 'error'}),
                new transports.File({filename: 'logs/activity/activity.log', level:'info'})
            ]
        });
    

    I used 'format.combine()'. Since I needed timestamp on all my transports, I added the formatting option within the createLogger, rather than inside each transport. My output on console and on file (activity.log) are as follows:

    {"message":"Connected to mongodb","level":"info","timestamp":"2018-02-01T22:35:27.758Z"}
    {"message":"Connected to mongodb","level":"info","timestamp":"2018-02-01T22:35:27.758Z"}
    

    We can add formatting to this timestamp in 'format.combine()' as usual using:

    format.timestamp({format:'MM-YY-DD'})
    

提交回复
热议问题