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.

Revisions

  1. hispanic revised this gist Nov 29, 2015. 1 changed file with 6 additions and 0 deletions.
    6 changes: 6 additions & 0 deletions vertically-aligned-log-formatter.js
    Original file line number Diff line number Diff line change
    @@ -1,3 +1,9 @@
    /**
    * 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.
    *
  2. hispanic created this gist Nov 29, 2015.
    40 changes: 40 additions & 0 deletions vertically-aligned-log-formatter.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,40 @@
    /**
    * 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;
    };