Skip to content
dc edited this page Jan 26, 2016 · 1 revision

Understanding Logging

Logging can be hard to understand in Vorpal. This is due to the fact that Vorpal does some complicated things in order to pipe logging between commands. This page attempts to explain it clearly.

Logging within a command

When logging within the context of a Vorpal command's action, it is important to always use this.log. The keyword this refers to a Vorpal CommandInstance, which carries a special log method.

vorpal
  .command('echo [command]')
  .action(function(args, callback) {
    // This will properly log to your terminal.
    this.log(args.command);
    // This will create problems.
    console.log(args.command); 
    callback();
  });

Using this method is important. Vorpal commands can pipe logging (called stdout) between processes.

Take the following example:

vorpal-app$ echo foo | reverse | capitalize

In this case, this.log above will pipe the word foo to the reverse command's stdin. The reverse command will then use its own this.log to again pipe its own output to the last command, capitalize. The full code to implement this is below:

vorpal.command('echo [command]')
  .action(function(args, cb) {
    this.log(args.command);
    cb();
  });

vorpal.command('reverse')
  .action(function(args, cb) {
    this.log(args.stdin.split('').reverse().join(''));
    cb();
  });

vorpal.command('capitalize')
  .action(function(args, cb) {
    this.log(args.stdin.toUpperCase());
    cb();
  });

The this.log method makes the above possible.

Logging outside out of a command

You may come across a situation where you need to log something independent of a Vorpal command. For instance, suppose you want to message the user of your application upon starting it.

const vorpal = new Vorpal().show();
console.log('Welcome to my amazing app!');

Using console.log as above would create a problem as it would get in the way of the user's prompt, making an ugly situation. You can't use this.log, because you are not in the context of a CommandInstance.

The solution in this case is to use vorpal.log:

const vorpal = new Vorpal().show();
vorpal.log('Welcome to my amazing app!');

The vorpal.log method will ensure your logging is drawn properly, but it will not pipe content through commands.

Summary

  1. Within the context of a Vorpal command, always use this.log.
  2. Outside of the context of a Vorpal command, always use vorpal.log.
  3. Never use console.log.