We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Use the Logger

So log.Printf seems to work well... but there's a better way!

A "logger" is an instance of a log.Logger that can be used to produce logs. Generally it's better to use a logger object than the log package's functions directly, for a few reasons:

  • You can easily change where the logs go, all in one place
  • You can add prefixes to the logs, again all in one place
  • You can change where the logs go at runtime, again... all in one place

Using STDERR

It's usually best to send logs to os.Stderr instead of os.Stdout because STDOUT is typically used for the main output of a program, and we don't want to gum that up with logs meant for developers.

When you create a new logger with log.New, you can specify the output destination, and os.Stderr is usually the right choice.

// create a logger
var logger = log.New(os.Stderr, "MESSAGE: ", log.LstdFlags)

// use a logger
logger.Printf("The Lisan al-Gaib arrived")
// MESSAGE: 2024/06/01 12:00:00 The Lisan al-Gaib arrived
  • os.Stderr is the standard error output stream
  • The second argument is a prefix for the log messages (here we're using "MESSAGE: ")
  • The third argument is the log flags, which can include things like timestamps, file names, and line numbers. log.LstdFlags simply includes the date and time.

Enforcing Loggers

If you find yourself forgetting to use a logger, the golangci-lint linter comes with a sublinter called forbidigo that can be configured to prohibit the use of these functions:

version: "2"

linters:
  settings:
    forbidigo:
      forbid:
        - pattern: ^fmt\.Print.*$
          msg: Use logger instead.
      analyze-types: true

This is totally optional of course, but it's nice to know about.

Assignment

Move from package-level log calls to a shared logger instance.

go run . 2>&1 | sh -c 'trap "" INT; tee linko.out.log'

Run and submit the CLI tests from the root of the Linko repo.