

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 5
click for more info
Not enough gems
Cost: 6 gems
1: Logging in Go
incomplete
2: Use the Logger
incomplete
3: Logging Requests
incomplete
4: Global Logger vs. Dependency Injection
incomplete
5: Logger Configuration
incomplete
6: Logger Failure
incomplete
7: Buffered Logging
incomplete
8: Logger Cleanup
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
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
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 arrivedIf 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: trueThis is totally optional of course, but it's nice to know about.
Move from package-level log calls to a shared logger instance.
go run . 2>&1 | tee -i linko.out.logRun and submit the CLI tests from the root of the Linko repo.