- Node.js — How to add timestamp to logs using Winston library?
- Measuring Execution Times in JavaScript with console.time()
- #Measuring Execution Times the Classic Way
- #Measuring Execution Times Using console.time()
- #Displaying the Measured Duration in the Console
- #A Closing Word on High-Precision Timing
- JavaScript Promises in Depth
- console: timeLog() method
- Syntax
- Parameters
- Return value
- Description
- Examples
- Specifications
- Browser compatibility
- Found a content problem with this page?
- show log time every request in Express?
Node.js — How to add timestamp to logs using Winston library?
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 = require('winston'); const logger = createLogger(< format: format.combine( format.timestamp(), format.json() ), transports: [ new transports.Console(), new transports.File(), new transports.File() ] >);
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:
We can add formatting to this timestamp in ‘format.combine()’ as usual using:
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:
- Remove the console transport and add again with the timestamp option.
- Create your own Logger object with the timestamp option set to true.
var winston = require('winston'); winston.remove(winston.transports.Console); winston.add(winston.transports.Console, );
The second, and cleaner option:
var winston = require('winston'); var logger = new (winston.Logger)(< transports: [ new (winston.transports.Console)() ] >);
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.
This is great. I usually wrap this in a dedicated file so that I can easily get my configured logger from any file, i.e., I put the above code (option 2) in a new file logger.js, followed by module.exports = logger; then from any file I do var logger = require(‘./logger.js’) and can then do logger.info(‘hello’) from any file and get the same configuration of Winston.
This does not appear to work in the current version of Winston. Try one of the other answers instead.
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.splat!==undefined?`$`:" ")) ), transports: [ new (winston.transports.Console)(< level: loggerLevel >), ] >); module.exports = logger;
Does this also work for logger.info(‘Message’, someObject) ? I setup a custom format using combine and I can’t seem to get the someObject included in the log message.
I was able to get someObject included by using the following printf statement $
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
var util = require('util'); util.log("something with timestamp");
The output will look something like this to out.log file:
15 Mar 15:09:28 - something with timestamp
I took Biswadev’s answer and created a stringified JSON object. This way if i need to process the logs later it will be in a well structured format.
const winston = require('winston'); const < createLogger, format, transports >= require('winston'); const dotenv = require('dotenv'); dotenv.config(); var logger = createLogger(< level: 'info', format: format.combine( format.timestamp(< format: 'YYYY-MM-DD HH:mm:ss', >), format.printf((info) => JSON.stringify(< t: info.timestamp, l: info.level, m: info.message, s: info.splat !== undefined ? `$` : '', >) + ',' ) ), >); if (process.env.NODE_ENV !== 'PRODUCTION') < logger.add(new transports.Console(< format: winston.format.cli() >)); // Turn these on to create logs as if it were production // logger.add(new transports.File(< filename: 'log/output/error.log', level: 'error' >)); // logger.add(new transports.File(< filename: 'log/output/warn.log', level: 'warn' >)); // logger.add(new transports.File(< filename: 'log/output/info.log', level: 'info' >)); > else < logger.add(new transports.File(< filename: 'log/output/error.log', level: 'error' >)); logger.add(new transports.File(< filename: 'log/output/warn.log', level: 'warn' >)); logger.add(new transports.File(< filename: 'log/output/info.log', level: 'info' >)); > module.exports = < logger, >;
app.listen(port, () => logger.info(`app is running on port $`));
info: app is running on port 3001
Measuring Execution Times in JavaScript with console.time()
Last week, I blogged about advanced JavaScript debugging with console.table() showcasing the console.table() function. Today, I want to show you another debugging method, more specifically one for measuring execution times: Say hello to console.time() .
#Measuring Execution Times the Classic Way
Here’s a small JavaScript snippet which concatenates the first one million natural numbers:
var output = ""; for (var i = 1; i 1e6; i++) output += i; >
If you’re wondering what 1e6 means, it’s just a short way to write ten to the sixth power, which equals one million. It means exactly the same as the number literal 1000000 .
The script is very simple, yet takes a couple dozen milliseconds (about 150ms on my machine) to execute. How did I measure this time? I could’ve done something like this:
var output = ""; // Remember when we started var start = new Date().getTime(); for (var i = 1; i 1e6; i++) output += i; > // Remember when we finished var end = new Date().getTime(); // Now calculate and output the difference console.log(end - start);
This approach is very straightforward. It also has the advantage that it runs pretty much everywhere. If you’re using a modern browser though, there’s a shorthand method for measuring durations and logging them to the console. Let’s inspect console.time() now.
#Measuring Execution Times Using console.time()
Making use of console.time() , the code from before can be rewritten as this:
var output = ""; // Start timing now console.time("concatenation"); for (var i = 1; i 1e6; i++) output += i; > // . and stop. console.timeEnd("concatenation");
We’ve now managed to make the code more expressive and slightly shorter than before: The call to console.time() starts a timer with the name concatenation, which is later stopped by console.timeEnd() . The timer names passed to both function calls have to match in order for the measuring to work.
Note that console.time() and console.timeEnd() are only supported by modern browsers, starting with Chrome 2, Firefox 10, Safari 4, and Internet Explorer 11.
#Displaying the Measured Duration in the Console
Chrome 31 has written the following output to the console:
Here is what Firefox 25 gives us (notice the concatenation: timer started information):
Finally, here’s IE 11, which only logs the duration if the console is open at that time:
#A Closing Word on High-Precision Timing
If you need to measure time precisely, neither Date.getTime() nor console.time() will get you far. Check out John Resig’s blog post about the accuracy of JavaScript time to learn why.
There’s a different API for that purpose, though: the Performance interface, which is implemented by most modern browsers.
Also, make sure to check out my other posts about the Chrome Developer Tools:
JavaScript Promises in Depth
ES2015 brought a native Promise implementation to the JavaScript standard library. In this course, we’re going to take an in-depth look at how to use promises to model asynchronous operations in JavaScript.
console: timeLog() method
The console.timeLog() method logs the current value of a timer that was previously started by calling console.time() .
Syntax
timeLog() timeLog(label) timeLog(label, val1) timeLog(label, val1, /* …, */ valN)
Parameters
The name of the timer to log to the console. If this is omitted the label «default» is used.
Additional values to be logged to the console after the timer output.
Return value
Description
The console.timeLog() method logs the current value of a timer.
The method can be passed the name of a timer. This will attempt to log the value of a timer created with that name in a previous call to console.time() :
.time("reticulating splines"); reticulateSplines(); console.timeLog("reticulating splines"); // reticulating splines: 650ms
If the timer name is omitted, then the timer is named «default» :
.time(); reticulateSplines(); console.timeLog(); // default: 780ms
.time("default"); reticulateSplines(); console.timeLog(); // default: 780ms
If there is no corresponding timer, timeLog() logs a warning like:
Timer "timer name" doesn't exist.
You can log additional values to the console after the timer output:
.time(); reticulateSplines(); console.timeLog("default", "Hello", "world"); // default: 780ms Hello world
See Timers in the documentation for more details and examples.
Examples
.time("answer time"); alert("Click to continue"); console.timeLog("answer time"); alert("Do a bunch of other stuff…"); console.timeEnd("answer time");
The output from the example above shows the time taken by the user to dismiss the first alert box, followed by the cumulative time it took for the user to dismiss both alerts:
answer time: 2542ms debugger eval code:3:9 answer time: 4161ms - timer ended
Notice that the timer’s name is displayed when the timer value is logged using timeLog() and again when it’s stopped. In addition, the call to timeEnd() has the additional information, «timer ended» to make it obvious that the timer is no longer tracking time.
Specifications
Browser compatibility
BCD tables only load in the browser
Found a content problem with this page?
This page was last modified on Jun 26, 2023 by MDN contributors.
Your blueprint for a better internet.
show log time every request in Express?
I’ve some problem in here. I don’t know why this is happened. I put timestamps code with Moment.js library, not only with that library, recently i created manually for showing timestamps but when i send request, time not updated. I put datetime in my file route. But this is work in server file. So for example server.js
var express = require('express') var app = express() var moment = require('moment') app.use(function(req, res, next)< console.log(moment().format('HH:mm:ss') + ' From server.js') //Showing time now next(); >) app.use('/', index) app.listen(8001)
var express = require('express') var app = express() var router = express.Router() var moment = require('moment') var timestamps = moment().format('HH:mm:ss') router.get('/', function(req, res)< console.log(timestamps + ' From routes/index.js') >) module.exports = routes
[nodemon] 1.11.0 [nodemon] to restart at any time, enter `rs` [nodemon] watching: *.* [nodemon] starting `node ./bin/www` 16:20:51 From Server.js 16:20:51 From routes/index.js
[nodemon] 1.11.0 [nodemon] to restart at any time, enter `rs` [nodemon] watching: *.* [nodemon] starting `node ./bin/www` 16:22:52 From Server.js 16:20:51 From routes/index.js
Nah, the second request still get existing time log from first request, this is only happened in routes. But work with well in server.js Is it happened because variable timestamps outside function? But when i running without variable, it’s worked.
router.get('/', function(req, res)< console.log(moment().format('HH:mm:ss') + ' From routes/index.js') >)