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

Logging in Go

The Go standard library has a built-in log package that we can use to produce messages with timestamps and other metadata, for example:

fmt.Println("This is a non-log message")
// This is a non-log message

log.Println("This is a log message")
// 2023/10/01 12:00:00 This is a log message

You might think, "why do I need a whole package for that? Can't I just use fmt.Println with a timestamp?" And... yes, you can. But there are some really great things about using a logging package! For example:

  • You can easily change where the logs go (e.g., to a file, to STDERR, or to a third-party service).
  • Timestamp functionality and other metadata management is built-in
  • Fatal errors can automatically exit the program (e.g. log.Fatal)
  • Most loggers provide fine-grained control over which logs to emit with log levels (e.g., INFO, DEBUG, ERROR).

Avoid fmt.Println or fmt.Fprint (and related functions) for logging in services! They're good for doing "normal" stdout-type stuff in CLI tools, but they're not purpose-built for logging.

Admittedly, the base log package in Go is pretty bare-bones, but don't worry we'll cover the more advanced log/slog in a later chapter.

What About Syslog?

There's also a log/syslog package, which is meant to send logs to the system's syslog service... but I'd advise against that in almost all cases. It's considered a bit of a wart, even by the Go team.

If you're targeting syslog, you're probably better off just using a syslog adapter for the slog package like slog-syslog.

Assignment

Switch Linko's app logs from fmt to the log package.

  1. Omit \n when using log.Printf (or slog). Both automatically append a newline.

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.