Member-only story

Effective Logging with log/slog in Go Projects

Beck Moulton
3 min readOct 24, 2023

--

Introduction

In Go language project development, efficient log searching and filtering are crucial for debugging. However, the standard library’s “log” package does not provide structured logging, making it less convenient. In Go 1.21.0, a new structured logging package, “log/slog,” was introduced to address this issue. It supports key-value pair formatting. This article will explore how to use “log/slog.”

Usage of log/slog

The default logger of “log/slog” utilizes the default logger of the “log” package, making it easy to get started. “log/slog” defines four log levels: Info, Debug, Warn, and Error, each with corresponding functions.

Example:

func main() {
log.Println("This is log")
slog.Debug("This is Debug Level")
slog.Info("This is Info Level")
slog.Warn("This is Warn Level")
slog.Error("This is Error Level")
}

Output:

2023/10/06 11:18:04 This is log
2023/10/06 11:18:04 INFO This is Info Level
2023/10/06 11:18:04 WARN This is Warn Level
2023/10/06 11:18:04 ERROR This is Error Level

In the code above, you’ll notice that the output of “log/slog” is very similar to “log,” with the addition of log levels between the timestamp and log message. This is because “log/slog” uses the default logger of “log.”

Apart from the four log level functions, there is also a “log” function that…

--

--

Beck Moulton
Beck Moulton

Written by Beck Moulton

Focus on the back-end field, do actual combat technology sharing Buy me a Coffee if You Appreciate My Hard Work https://www.buymeacoffee.com/BeckMoulton

No responses yet