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.
-
Open
src/commands/hello/world.ts
and update the import from@salesforce/core
to include theLogger
class: -
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 theLogger.child()
method. To try it out, replace therun
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 tothis.ctor.name
which points to the name of the command class (World
in our case). But it can be anything you want. -
Now make the logger print records to the terminal. First set the
DEBUG
environment variable, either to*
to see all log records orsf:_LoggerName_
to filter records by logger.For now, let's print logs for only the
hello world
command:For bash/zsh:
For PowerShell:
-
Run the
hello world
command usingbin/dev
as usual:You see log and command output similar to this:
-
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.