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!
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.
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.
To create a logger, we first need to import the log/slog package and then initialize a logger instance.
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.
Now that we have our logger, we can start logging messages using the Info, Error, and other methods provided by the slog package.
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.
The slog package allows you to customize the format of your log messages using the NewJSONHandler function's Formatter option.
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.
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! šÆ