The most basic way to output an error message:
import "os"
fmt.Fprintf(os.Stderr, "error message")
A more sophisticated way to deal with logs would be with log/slog.
A simple usage of this package would be something like this:
import "log/slog"
func main() {
slog.Debug("debug message, very detailed")
slog.Info("info message, general")
slog.Warn("warning message, potential issue")
slog.Error("error message, serious issue")
}
Would produce an output similar to this:
2025/06/11 10:27:25 INFO info message, general
2025/06/11 10:27:25 WARN warning message, potential issue
2025/06/11 10:27:25 ERROR error message, serious issue
By default, slog doesn't print debug logs, but we can change that with the following instruction:
slog.SetLogLoggerLevel(slog.LevelX)
Also, the default logger always print to stderr and the output format is plain text with few details, but we can change this behavior if needed by creating our own logger, check the HandlerOptions.
We have the following levels of debug:
- LevelDebug
- LevelInfo
- LevelWarn
- LevelError
And we can define AddSource = true
, to include details about the source code.
Putting everything together:
package main
import (
"log/slog"
"os"
)
func main() {
logger := slog.New(slog.NewJSONHandler(os.Stdout,
&slog.HandlerOptions{
Level: slog.LevelDebug,
AddSource: true,
}))
slog.SetDefault(logger)
slog.Debug("debug message, very detailed")
slog.Info("info message, general")
slog.Warn("warning message, potential issue")
slog.Error("error message, serious issue")
}
Would produce an output similar to this:
{
"time": "2025-06-11T11:05:49.077787203-03:00",
"level": "DEBUG",
"source": {
"function": "main.main",
"file": "/home/fk/dev/go/slog_tests/slog_tests.go",
"line": 17
},
"msg": "debug message, very detailed"
}
{
"time": "2025-06-11T11:05:49.077913712-03:00",
"level": "INFO",
"source": {
"function": "main.main",
"file": "/home/fk/dev/go/slog_tests/slog_tests.go",
"line": 18
},
"msg": "info message, general"
}
{
"time": "2025-06-11T11:05:49.077917689-03:00",
"level": "WARN",
"source": {
"function": "main.main",
"file": "/home/fk/dev/go/slog_tests/slog_tests.go",
"line": 19
},
"msg": "warning message, potential issue"
}
{
"time": "2025-06-11T11:05:49.077920535-03:00",
"level": "ERROR",
"source": {
"function": "main.main",
"file": "/home/fk/dev/go/slog_tests/slog_tests.go",
"line": 20
},
"msg": "error message, serious issue"
}
Top comments (0)
Some comments may only be visible to logged-in visitors. Sign in to view all comments. Some comments have been hidden by the post's author - find out more