Skip to content

Instantly share code, notes, and snippets.

@hispanic
Last active November 29, 2015 20:35
Show Gist options
  • Save hispanic/c75d3dea56a317c67e8d to your computer and use it in GitHub Desktop.
Save hispanic/c75d3dea56a317c67e8d to your computer and use it in GitHub Desktop.
Log formatter for winston that enforces vertically-aligned log entry components
/**
* The fixed (both minimum and maximum) length of the "level" property in each log entry.
* Longer values will be truncated, while shorter values will be right-padded with spaces.
*/
var levelLength = 5;
/**
* Custom log formatter that enforces vertically-aligned log entry components.
*
* @param options - See winston/common.log() for available properties.
*/
var logFormatter = function(options) {
/*
* The requested level for this log entry, in plain-text. We need to go back to the source
* (options) instead of parsing the output because the output might be colorized (encoded).
*/
var levelFull = options.level;
var levelForDisplay = levelFull;
// Pad the level.
if (levelLength > String(levelFull).length) {
levelForDisplay = levelFull + Array(levelLength - String(levelFull).length + 1).join(' ');
}
// And then truncate the level.
levelForDisplay = levelForDisplay.substring(0, levelLength);
/**
* If the level has been colorized, we need to repeat this colorization of both the search
* and replacement strings.
*/
if (options.colorize === 'all' || options.colorize === 'level' || options.colorize === true) {
levelForDisplay = colors[logColors[levelFull]](levelForDisplay);
levelFull = colors[logColors[levelFull]](levelFull);
}
// Unset the formatter in the options argument so we don't end up in an infinite loop.
options.formatter = null;
// Start with winston's default output format.
var output = winstonCommon.log(options);
// Perform the actual replacement.
output = output.replace(levelFull, levelForDisplay);
return output;
};
@hispanic
Copy link
Author

For more information, please see Fixed-Length Level Logging in Winston.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment