How to log errors using 'log/slog'

PHPz
Release: 2024-02-06 11:24:03
forward
628 people have browsed it

How to log errors using log/slog

Question content

The official documentation shows how to use the new structured logging package, but seems to omit how to log errors.

https://pkg.go.dev/log/slog

package main

import (
    "fmt"
    "log/slog"
    "os"
)

func demoFunction() error {
    return fmt.Errorf("oh no: %v", 123)
}

func main() {
    logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
    slog.SetDefault(logger)

    slog.Info("info demo", "count", 3)
    slog.Warn("warn demo", slog.String("somekey", "somevalue"))
    slog.Error("error demo", slog.Int("someintkey", 123))
    err := demoFunction()
    if err != nil {
        // Here I'm logging the error as a string, but I presume there is a better way
        // possibly that will log stack trace info as well.
        slog.Error("the demo function got an error.", slog.String("error", err.Error()))
    }
}
Copy after login


Correct answer


Someone made a proposal and closed it. I think it ends up being unnecessary syntactic sugar.

It seems that some people have decided to wrap slog.Any calls

func ErrAttr(err error) slog.Attr {
    return slog.Any("error", err)
}
Copy after login

The above is the detailed content of How to log errors using 'log/slog'. For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template