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

Logger Configuration

It's more standard to decide what goes to STDERR and what goes to a file based on the environment your application is running in, rather than on separate loggers. Common environments are:

  • "development" (local development, like when you're running the application on your own machine)
  • "staging" (a pre-production environment that mimics production)
  • "production" (the live environment that users interact with)

Multiwriter Configuration

There's no reason a logger can't write to both STDERR and a file at the same time! The io.MultiWriter function takes multiple io.Writer objects and returns a single io.Writer that writes to all of them. For example:

file, err := os.OpenFile(logFile, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0o644)
if err != nil {
	log.Fatalf("failed to open log file: %v", err)
}
multiWriter := io.MultiWriter(os.Stderr, file)
logger := log.New(multiWriter, "INFO: ", log.LstdFlags)

Assignment

Use one logger that changes output based on LINKO_LOG_FILE.

Assume that in production, Linko has a LINKO_LOG_FILE environment variable set. In local development and staging, it is not set.

If LINKO_LOG_FILE is set, the logger should write to both the file and STDERR. Otherwise, it should only write to STDERR.

Restart your server, setting the LINKO_LOG_FILE environment variable so the tests can verify the file is created:

LINKO_LOG_FILE=linko.access.log go run .

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