Add Logging

Add logging to your plugin with the Logger class from @salesforce/core.

Let's show how to add logging to the initial hello world command that sf dev generate plugin generated.

  1. Open src/commands/hello/world.ts and update the import from @salesforce/core to include the Logger class:

  2. Now create child logger instance. The Logger class creates a root logger with some defaults. Other code, like a command or library, then creates a child logger using the Logger.child() method. To try it out, replace the run method with this code:

    The example shows how you pass the name of the child logger as the first argument of Logger.child(). In the example, it's set it to this.ctor.name which points to the name of the command class (World in our case). But it can be anything you want.

  3. Now make the logger print records to the terminal. First set the DEBUG environment variable, either to * to see all log records or sf:_LoggerName_ to filter records by logger.

    For now, let's print logs for only the hello world command:

    For bash/zsh:

    For PowerShell:

  4. Run the hello world command using bin/dev as usual:

    You see log and command output similar to this:

  5. Remember to unset the DEBUG environment variable after you're done:

    For bash/zsh:

    For PowerShell:

The Logger class wraps pino, which already sets log levels. See logger.levels for more information.

Salesforce CLI saves logs to a file in the global .sf folder; you can turn off this behavior by setting the SFDX_DISABLE_LOG_FILE environment variable to true. The CLI starts a new log file every day, formatted like sf-YYYY-MM-DD.log. The CLI cleans them up if they're more than 7 days old.

Salesforce CLI saves log records to a log file only if the log level method used is the same level or higher than the level set in the logger instance.

Let's see how this works. By default, the root logger sets the log level to warn. This example shows calls to debug, warn, and error methods, but only the warn and error records are saved to the log file:

The user can set the log level with environment variables (SF_LOG_LEVEL=debug or SF_LOG_LEVEL=trace) so it's best not to rely on code to manage your child Logger. Rather,let the user control the log level.