Skip to content

Logging

maxlandon edited this page May 29, 2023 · 5 revisions

One of the things that has (bizarrely) lacked in most console applications until now is an efficient synchronisation mechanism for allowing logging arbitrary output to the console while:

  • Not needlessly refreshing the prompt (such as when a command is executing)
  • Actually refreshing the prompt and the current input line correctly, when needed.
  • Optionally, offer a unified way of logging output, without having to consider in which state the console is.

The console thus offers two very simple methods for logging -command or other- output to your application.

Transient log

The first method will actually "push" the prompt below a log line to be printed. In detail, the current prompt/line/helpers are cleared, the log output is printed, and the prompt/line is redisplayed below it.

func (c *Console) TransientPrintf(msg string, args ...any)

You might use something like this snippet for logging asynchronous things (generally coming from somewhere else than a command's run function):

asyncLog <-logChan

// Refresh the prompt just below.
console.TransientPrintf(asyncLog.String())

And/or from within a command runner:

func myCommandRun(cmd *cobra.Command, args []string) error {
    console.TransientPrintf("Starting the command")
    ... do stuff ...
    console.TransientPrintf("Doing stuff")
}

Note: You will probably may be able to wrap this TransientPrintf function into a more versatile logging routine, with different log levels, etc.

Classic prompt log

There may be some cases, though, where you want the current prompt to be left as is, your log event to be printed below it, and a new prompt/input line to be displayed below. For this, the following method is given:

func (c *Console) Printf(msg string, args ...any)

Note that you might actually end up only using the TransientPrintf() function

Behavior when a command is executing

Both of the methods above take into account whether the console is currently executing a command: this allows you to reuse the same log function in all cases, while benefiting an adjusted behavior. When the console is currently executing a command, the prompt will not be redisplayed, so that your log output just looks like normal command output. logging