Go log/slog: Structured Logging for Go (Go 1.21+)

beginner
21 min

Go log/slog: Structured Logging for Go (Go 1.21+)

Welcome to our comprehensive guide on Go's log/slog package! In this lesson, we'll explore the structured logging functionality that's been a part of Go since version 1.21. Let's get started!

Understanding Structured Logging

Structured logging is a technique used to make logs more machine-readable and easier to analyze. Instead of simply logging textual messages, we structure them into key-value pairs for better processing.

šŸ’” Pro Tip: Structured logs help in filtering, aggregating, and correlating logs effectively, making them invaluable for debugging and monitoring applications.

Introduction to Go's log/slog Package

The log/slog package is Go's built-in solution for structured logging. It provides a simple and flexible API for logging messages, with built-in support for JSON serialization.

Creating a Logger

To create a logger, we first need to import the log/slog package and then initialize a logger instance.

go
package main import ( "log/slog" "os" ) func main() { // Initialize the logger logger, err := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{LevelReuse: true})) if err != nil { panic(err) } // Now we can use the logger to log messages }

šŸ“ Note: In the above example, we create a logger using the slog.NewJSONHandler() function, which writes logs to the standard output (os.Stdout). The LevelReuse option ensures that the logger's level is not reset after each log entry.

Logging Messages

Now that we have our logger, we can start logging messages using the Info, Error, and other methods provided by the slog package.

go
import ( // ... "time" ) func main() { // ... // Log an informational message logger.Info("Starting application", slog.Int("process_id", os.Getpid()), slog.Time("start_time", time.Now())) }

šŸ’” Pro Tip: When logging, it's good practice to include relevant metadata such as timestamps, process IDs, and request IDs to make logs more meaningful.

Formatting Log Messages

The slog package allows you to customize the format of your log messages using the NewJSONHandler function's Formatter option.

go
func main() { // ... // Create a custom logger with a custom formatter formatter := slog.NewJSONFormatter(slog.FmtTimeRFC3339, slog.FmtLevelText, slog.FmtFieldData) logger, err := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{LevelReuse: true, Formatter: formatter})) // ... }

šŸ“ Note: In the above example, we create a custom formatter that formats timestamps using RFC 3339, levels as text, and data as JSON.

Quiz

Quick Quiz
Question 1 of 1

What is structured logging, and why is it useful?

That's it for this lesson! In the next lesson, we'll delve deeper into Go's log/slog package, exploring more advanced topics like log rotation, custom formats, and logger levels. Stay tuned! šŸŽÆ