What is console-stamp?
The console-stamp npm package is used to add timestamps to console output in Node.js applications. It enhances the standard console methods (log, info, warn, error) by prefixing them with a timestamp, making it easier to track when specific log entries were made.
What are console-stamp's main functionalities?
Basic Timestamping
This feature adds a basic timestamp to all console log messages. By requiring the console-stamp package and passing the console object to it, all subsequent console.log calls will include a timestamp.
const consoleStamp = require('console-stamp')(console);
console.log('This is a log message.');
Custom Timestamp Format
This feature allows you to customize the format of the timestamp. By passing an options object with a 'format' property, you can specify the desired timestamp format.
const consoleStamp = require('console-stamp')(console, { format: 'yyyy-mm-dd HH:MM:ss.l' });
console.log('This is a log message with a custom format.');
Custom Label
This feature adds a custom label to the log messages. By setting the 'label' property to true in the options object, you can include a label in the log output.
const consoleStamp = require('console-stamp')(console, { label: true });
console.log('This is a log message with a custom label.');
Custom Prefix
This feature allows you to add a custom prefix to the log messages. By setting the 'prefix' property in the options object, you can include a custom prefix in the log output.
const consoleStamp = require('console-stamp')(console, { prefix: '[LOG]' });
console.log('This is a log message with a custom prefix.');
Other packages similar to console-stamp
winston
Winston is a versatile logging library for Node.js that supports multiple transports (e.g., console, file, HTTP). It provides more advanced logging features compared to console-stamp, such as log levels, custom formats, and log rotation.
bunyan
Bunyan is a simple and fast JSON logging library for Node.js. It provides structured logging with JSON output, making it easier to parse and analyze logs. Unlike console-stamp, Bunyan focuses on structured logging rather than just adding timestamps.
log4js
Log4js is a logging library inspired by the Java log4j library. It supports multiple appenders (e.g., console, file, SMTP) and provides flexible configuration options. Log4js offers more comprehensive logging capabilities compared to console-stamp.
Console-stamp 3.0.0 RC1
This module enables you to patch the console's methods in Node.js, to add prefix based on tokens, and more...
Usage
Install
npm install console-stamp@next
Simple example
This simple example is using the default settings
require('console-stamp')(console);
console.log('Hello, World!');
Patching the console
require('console-stamp')(console, [options]);
console
The global console or custom console.
options {Object|String}
The second parameter is an object with several options. As a feature this parameter can be a string containing the date-format.
-
options.format {String}
A string with date format based on dateformat
Default: 'dd.mm.yyyy HH:MM:ss.l'
-
options.tokens {Object}
Containing token-functions. See example here.
-
options.include {Array}
An array containing the methods to include in the patch
Default: ["debug", "log", "info", "warn", "error"]
-
options.level {String}
A string choosing the most verbose logging function to allow.
Default: log
-
options.extend {Object}
An object describing methods and their associated log level, to extend the existing method <-> log level
pairs.
For an example see Custom methods.
-
options.stdout {WritableStream}
A custom stdout
to use with custom console.
Default: process.stdout
-
options.stderr {WritableStream}
A custom stderr
to use with custom console.
Default: options.stdout
or process.stdout
Note also that by sending the parameter --no-color
when you start your node app, will prevent any colors from console.
$ node my-app.js --no-color
Tokens
There are only two tokens registered by default:
:date([format][,utc])[.color]
:label([padding])[.color]
:date([format][,utc])
- format {String}
Containing the date format based on dateformat
Default: 'dd.mm.yyyy HH:MM:ss.l' - utc {Boolean}
Set to true
if ouy wath UTC-time
Default: false
:label([padding])
- padding {Number}
The total length of the label, including the brackets and padding
Default: 7
Making a custom date token using moment.js
const moment = require('moment');
moment.locale('ja');
require('console-stamp')(console, {
format: ':mydate() :label(7)',
tokens:{
mydate: () => {
return `[${moment().format('LLLL')}]`;
}
}
});
console.log('This is a console.log message');
console.info('This is a console.info message');
console.debug('This is a console.debug message');
console.warn('This is a console.warn message');
console.error('This is a console.error message');
Result:
[2016年5月12日午前11時10分 木曜日] [LOG] This is a console.log message
[2016年5月12日午前11時10分 木曜日] [INFO] This is a console.info message
[2016年5月12日午前11時10分 木曜日] [DEBUG] This is a console.debug message
[2016年5月12日午前11時10分 木曜日] [WARN] This is a console.warn message
[2016年5月12日午前11時10分 木曜日] [ERROR] This is a console.error message
Colors and styling
All tokens can have a trailing styling like this:
require('console-stamp')(console, {
format: ':foo().blue.bgWhite.underline :label(7)',
tokens:{
foo: () => {
return 'bar';
}
}
});
Example
require('console-stamp')(console, { format: ':date(dd/mm/yyyy HH:MM:ss.l) :label' });
console.log('Hello World!');
const port = 8080;
console.log('Server running at port %d', port);
console.log('This is a console.log message');
console.info('This is a console.info message');
console.debug('This is a console.debug message');
console.warn('This is a console.warn message');
console.error('This is a console.error message');
Result:
[26/06/2015 12:44:31.777] [LOG] This is a console.log message
[26/06/2015 12:44:31.777] [INFO] This is a console.info message
[26/06/2015 12:44:31.778] [DEBUG] This is a console.info message
[26/06/2015 12:44:31.779] [WARN] This is a console.warn message
[26/06/2015 12:44:31.779] [ERROR] This is a console.error message
Custom Console
You can also create a custom console with its own stdout
and stderr
like this:
const fs = require('fs');
const output = fs.createWriteStream('./stdout.log');
const errorOutput = fs.createWriteStream('./stderr.log');
const logger = new console.Console(output, errorOutput);
console_stamp(logger, {
stdout: output,
stderr: errorOutput
});
Everything is then written to the files.
NOTE: If stderr
isn't passed, warning and error output will be sent to the given stdout
.
Custom Methods
The option.extend option enables the extension or modification of the logging methods and their associated log levels:
The default logging methods and their log levels are as follows:
levels: {
error: 1,
warn: 2,
info: 3,
log: 4,
debug: 4,
};
The extend option enables the usage of custom console logging methods to be
used with this module, for example:
console.fatal = function(msg) {
console.org.error(msg);
process.exit(1);
}
require('console-stamp')(console, {
extend: {
fatal: 1
}
});
Note how the console.org.error
method used in the custom method. This is to prevent circular calls to log