Who does not love logging? Heard of a lightweight, extensible, configurable logging library written in Golang - slog. Quick review on how to use it for my reference.

package main

import (

func main() {
	slog.Debug("This is DEBUG message")
	slog.Info("This is INFO message")
	slog.Notice("This is NOTICE message")
	slog.Warn("This is WARNING message")
	slog.Error("This is ERROR message")
	slog.Fatal("This is FATAL message")

Here is the output:

go slog terminal output

Color could be disabled (enabled by default):

	slog.Configure(func(logger *slog.SugaredLogger) {
		f := logger.Formatter.(*slog.TextFormatter)
		f.EnableColor = false

Logging in JSON:

	// use JSON formatter

go slog json format

From the pkg readme - How to log into the file:

func main() {
	defer slog.MustFlush()

	// DangerLevels contains: slog.PanicLevel, slog.ErrorLevel, slog.WarnLevel
	h1 := handler.MustFileHandler("/tmp/error.log", handler.WithLogLevels(slog.DangerLevels))

	// NormalLevels contains: slog.InfoLevel, slog.NoticeLevel, slog.DebugLevel, slog.TraceLevel
	h2 := handler.MustFileHandler("/tmp/info.log", handler.WithLogLevels(slog.NormalLevels))


	// add logs
	slog.Info("info message text 1")
	slog.Error("error message text 1")
	slog.Info("info message text 2")
	slog.Error("error message text 2")

go slog terminal output