SoFunction
Updated on 2025-03-05

Introduction to the usage of golang structured log slog

Logging is an important part of any software, and Go provides a built-in log package (slog). However, as the complexity of the application continues to increase, the demand for structured logs is becoming increasingly obvious. Structured logs allow developers to record data in a structured format, which facilitates the analysis and analysis of log aggregation tools. Currently, the most commonly used in the industry is: zap.

In this article, I will briefly introduce the slog package, its features, and how to use it in a Go application.

What is slog

slogProvides structured logging, which includes a message, level, and various other attributes represented by key-value pairs.

use

Latest1.21Version has been introducedslog. To use in a Go projectslog, it can be imported in the following ways:

import "log/slog"

Here is a very simple example:

func main() {
	("hello, world!", "coding", "happy")
}

Output:

2023/09/15 13:42:27 INFO hello, world! coding=happy

Function

slogProvides many useful features that make it a powerful logging package for Go. Here are some of the main features:

  • Structured logs
  • Severe level log
  • Grouping log
  • Custom processing

Structured logs

slogThere are two ways to provide by default:

  • TextHandler
  • JSONHandler

Let's write an example of using these two methods:

func main() {
	textHandler := (, nil)
	textLogger := (textHandler)
	("TextDemo",
		("app-version", "v0.0.1"),
		("release-version", 1),
	)
	jsonHandler := (, nil)
	jsonLogger := (jsonHandler)
	("JsonDemo",
		("app-version", "v0.0.1"),
		("release-version", 1),
	)
}

The output is:

time=2023-09-15T13:48:37.424+08:00 level=INFO msg=TextDemo app-version=v0.0.1 release-version=1
{"time":"2023-09-15T13:48:37.4647782+08:00","level":"INFO","msg":"JsonDemo","app-version":"v0.0.1","release-version":1}

From the above we can see that the code uses similarMethod,slogProvides the function of specifying attributes. There are many types of attributes to choose from:

  • : String attribute.
  • : Integer attribute.
  • slog.Float64: Floatpoint property.
  • : Boolean property.
  • : Duration attribute.
  • : Time attribute.
  • : Group attributes, which can be used to group related attributes
func main() {
	jsonHandler := (, nil)
	jsonLogger := (jsonHandler)
	(
		"attributes",
		("version", "1.0.0"),
		("app-version", 1),
		slog.Float64("point-value", 1.2),
		("status", true),
		("duration", *1),
		("time", ()),
		(
			"request",
			("path", "<>"),
			("method", "get"),
		),
	)
}

I've formatted the corresponding output:

{
  "time": "2023-09-15T13:53:43.8848272+08:00",
  "level": "INFO",
  "msg": "attributes",
  "version": "1.0.0",
  "app-version": 1,
  "point-value": 1.2,
  "status": true,
  "duration": 3600000000000,
  "time": "2023-09-15T13:53:43.8848272+08:00",
  "request": {
    "path": "<>",
    "method": "get"
  }
}

Severe level log

This allows us to record information of different severity.slogFour log levels are provided by default, each level has an integer value:

  • DEBUG(-4)
  • INFO(0)
  • WARN(4)
  • ERROR(8)

example:

func main() {
	jsonHandler := (, &{
		Level: ,
	})
	jsonLogger := (jsonHandler)
	("Hello, world!")
	("Hello, world!")
	("Hello, world!")
	("Hello, world!")
}

NOTE: RememberNewHandlerSet the level when set.

Grouping log

Grouping logs refers to the practice of classifying log information into logical groups or categories.SlogSupport grouped logging by using attributes or key-value pairs associated with logging.

example:

func main() {
	jsonHandler := (, &{
		Level: ,
	})
	jsonLogger := (jsonHandler).WithGroup("request")
	("",
		("url", "<>"),
		("method", "GET"),
		("response-code", 200),
	)
}

Here is a better practice:

  • Define a logger of the request group in the middleware of the http service, and print out some information about 4xx, 5xx and other requests.
  • For ordinary business, we can use a service group logger

Custom processing

slogAbility to create customhandler, write log information to different destinations, such as files, databases, or external services.

slogThe provided handler interface defines the methods that custom handlers must implement. There are four methods for handling program interfaces:

type Handler interface {
    Enabled(Level) bool
    Handle(Record) error
    WithAttrs([]Attr) Handler
    WithGroup(string) Handler
}

Here is an example of how to create a customizable file that writes log information tohandler:

type FileHandler struct {
	file *
}
func NewFileHandler(filename string) (*FileHandler, error) {
	file, err := (filename, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
	if err != nil {
		return nil, err
	}
	return &FileHandler{file}, nil
}
func (h *FileHandler) Enabled(_ , level ) bool {
	return true
}
func (h *FileHandler) Handle(_ , record ) error {
	_, err := ( + "\n")
	return err
}
func (h *FileHandler) WithAttrs(attrs [])  {
	return h
}
func (h *FileHandler) WithGroup(name string)  {
	return h
}
func (h *FileHandler) Close() error {
	return ()
}
func main() {
	fileHandler, err := NewFileHandler("")
	if err != nil {
		panic(err)
	}
	defer ()
	logger := (fileHandler)
	("Hello, world!")
	("Debugging errors")
}

When running the program at this time, the console will not have the corresponding log output, but will output it to the corresponding file:

 slogDemo  cat .\
Hello, world!
Debugging errors

Summarize

slogIt is a powerful Go log package that provides structured logging capabilities. It is easy to use and provides many useful features such as level logging and custom handlers. If you are looking for a log package that meets your growing application needs,slogDefinitely worth your try.

This is the introduction to this article about the usage of golang structured log slog. For more related go slog content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!