How can I add timestamp to logs using Node.js libr

2019-03-14 05:30发布

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

7条回答
爷的心禁止访问
2楼-- · 2019-03-14 05:44

we could use console-stamp to add timestamp and log level to the existing console: require('console-stamp')(console, '[yyyy-mm-dd HH:MM:ss.l]')

See https://github.com/starak/node-console-stamp for the details

查看更多
Viruses.
3楼-- · 2019-03-14 05:48

Although I'm not aware of winston, this is a suggestion. I use log4js for logging & my logs by default look like this

[2012-04-23 16:36:02.965] [INFO] Development - Node Application is running on port 8090
[2012-04-23 16:36:02.966] [FATAL] Development - Connection Terminated to  '127.0.0.1' '6379'

Development is the environment of my node process & [INFO|FATAL] is log level

Maintaining different profiles for logging is possible in log4js. I have Development & Production profiles. Also there are logger types like rolling file appender, console appender, etc. As a addon your log files will be colorful based on the log level [Trace, Info, Debug, Error, Fatal] ;)

log4js will override your console.log It is a configurable parameter now in 0.5+

查看更多
冷血范
4楼-- · 2019-03-14 05:54

I was dealing with the same issue myself. There are two ways I was able to do this.

When you include Winston, it usually defaults to adding a Console transport. In order to get timestamps to work in this default case, I needed to either:

  1. Remove the console transport and add again with the timestamp option.
  2. Create your own Logger object with the timestamp option set to true.

The first:

var winston = require('winston');
winston.remove(winston.transports.Console);
winston.add(winston.transports.Console, {'timestamp':true});

The second, and cleaner option:

var winston = require('winston');
var logger = new (winston.Logger)({
    transports: [
      new (winston.transports.Console)({'timestamp':true})
    ]
});

Some of the other options for Console transport can be found here:

  • level: Level of messages that this transport should log (default 'debug').
  • silent: Boolean flag indicating whether to suppress output (default false).
  • colorize: Boolean flag indicating if we should colorize output (default false).
  • timestamp: Boolean flag indicating if we should prepend output with timestamps (default false). If function is specified, its return value will be used instead of timestamps.
查看更多
Fickle 薄情
5楼-- · 2019-03-14 05:56

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'})
查看更多
啃猪蹄的小仙女
6楼-- · 2019-03-14 05:56

We can do like this also

var winston = require('winston');
    const { createLogger, format, transports } = require('winston')
    var config = require('../configurations/envconfig.js');

    var loggerLevel = process.env.LOGGERLEVEL ||  config.get('LOGGERLEVEL');

    var logger = winston.createLogger({ format: format.combine(
            format.timestamp({
                format: 'YYYY-MM-DD HH:mm:ss'
            }),
            format.printf(info => `${info.timestamp} ${info.level}: ${info.message}`+(info.splat!==undefined?`${info.splat}`:" "))
        ), 
        transports: [
            new (winston.transports.Console)({ level: loggerLevel }),
           ]
    });
    module.exports = logger;
查看更多
forever°为你锁心
7楼-- · 2019-03-14 06:06

You can use built-in util and forever to achieve logging with timestap for your nodejs server. When you start a server add log output as part of the parameter:

forever start -ao log/out.log server.js

And then you can write util in your server.js

server.js

var util = require('util');
util.log("something with timestamp");

The output will look something like this to out.log file:

out.log

15 Mar 15:09:28 - something with timestamp
查看更多
登录 后发表回答