Cowork AI is developing various products using AI. Please show your interest! Learn more

Let's log in JSON format in Go

This article explores how to log in JSON format using the Go programming language.

In any program, logging is an essential tool to ensure that my program runs smoothly.

You can output logs for normal operation or logs for debugging purposes.

The Go language offers a log package by default, but it doesn’t provide sufficient functionality. It’s primarily used for basic system logging, and generally, external packages such as slog, introduced in Go 1.21, are preferred.

Before that, external solutions like zerolog and zap were utilized.

It wasn’t simply for convenience; they were also superior in performance. Previously, performance evaluations would be conducted in repository benchmarks to make adoption decisions.

Why is logging in JSON format necessary?

While it’s not necessary to log everything in JSON, if you use platforms that search through logs, there are times when more structured logging is required.

Nowadays, platforms are quite good at searching, but when logs are structured like JSON, not only does search performance improve, but it also allows for more complex queries.

For example, searching for level:info retrieves only the info level logs, while searching for level:info AND message:"hello" retrieves logs that are at the info level and include “hello” in the message.

Using the slog package

As mentioned earlier, while using external libraries is an option, the built-in package slog has developed so well recently that there’s rarely a need to use external solutions.

It generally includes all the features used in other libraries and offers decent performance.

package main

import (
    "log/slog"
)

func main() {
    slog.Info("Log test", // Message 
		"key1", "value1", // Custom Field-Value
		"key2", "value2", // Custom Field-Value
	)
}
2025/03/07 16:25:53 INFO Log test key=value

Outputting in JSON format

Outputting in JSON format isn’t difficult. You just need to set up the logger using slog.NewJSONHandler.

package main

import (
	"log/slog"
	"os"
)

func main() {
	logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
	slog.SetDefault(logger)
	slog.Info("Log test", // Message
		"key1", "value1", // Custom Field-Value
		"key2", "value2", // Custom Field-Value
	)
}

By creating a logger handled by JSONHandler and setting it as the system’s default, you can achieve this.

{"time":"2025-03-07T16:27:52.268722+09:00","level":"INFO","msg":"Log test","key1":"value1","key2":"value2"}

You can obtain results like this.

By default, both TextHandler and JSONHandler are provided, and TextHandler is used as the default.

You can also utilize values stored in ctx through context, which I will discuss later in a post about logging Request IDs.

Reference

Cookies
essential