go

Go中结构化日志的综合指南(2)

2023-03-24  本文已影响0人  Go语言由浅入深

上一篇文章我们介绍了目前go标准库存在的不足,以及新的slog库丰富的功能。

自定义日志处理程序(handler)

上一篇文章介绍,slog默认支持TextHandler和JSONHandler,但可以使用HandlerOptions类型进行自定义。前面学习了如何在日志属性之前调整最低级别和修改属性。另一个可以通过HandlerOptions完成的自定义是添加日志消息的来源:

func main() {

    opts := slog.HandlerOptions{
        AddSource: true,
        Level:     slog.LevelDebug,
    }
    logger := slog.New(opts.NewJSONHandler(os.Stdout))

    logger.Debug("Debug message")
    logger.Info("Info message")
    logger.Warn("Warning message")
    logger.Error("Error message")
}

output:

{"time":"2023-02-24T10:28:50.751111921+01:00","level":"DEBUG","source":"/home/betterstack/go-logging/main.go:55","msg":"Debug message"}
{"time":"2023-02-24T10:28:50.75120862+01:00","level":"INFO","source":"/home/betterstack/go-logging/main.go:56","msg":"Info message"}
{"time":"2023-02-24T10:28:50.751215229+01:00","level":"WARN","source":"/home/betterstack/go-logging/main.go:57","msg":"Warning message"}
{"time":"2023-02-24T10:28:50.751222025+01:00","level":"ERROR","source":"/home/betterstack/go-logging/main.go:60","msg":"Error message"}

根据应用程序环境切换处理程序也很容易。例如,你可能更喜欢使用TextHandler作为你的开发日志,因为它更容易阅读,然后在生产环境中切换到JSONHandler,以更好地兼容各种日志工具,你可以通过一个环境变量轻松地启用这种行为:

package main

import (
    "os"

    "golang.org/x/exp/slog"
)

var appEnv = os.Getenv("APP_ENV")

func main() {
    opts := slog.HandlerOptions{
        Level: slog.LevelDebug,
    }

    var handler slog.Handler = opts.NewTextHandler(os.Stdout)
    if appEnv == "production" {
        handler = opts.NewJSONHandler(os.Stdout)
    }

    logger := slog.New(handler)
    logger.Info("Info message")
}
go run main.go

output:

time=2023-02-24T10:36:39.697+01:00 level=INFO msg="Info message"
APP_ENV=production go run main.go

output:

{"time":"2023-02-24T10:35:16.964821548+01:00","level":"INFO","msg":"Info message"}

创建自定义日志处理程序(handler)

由于Handler是一个接口,可以轻松地定义一个接口,以不同的方式格式化日志或将它们写入某个目的地。接口定义如下:

type Handler interface {
    Enabled(context.Context, Level) bool
    Handle(r Record) error
    WithAttrs(attrs []Attr) Handler
    WithGroup(name string) Handler
}

上面每个函数的作用如下:

// NOTE: Not well tested, just an illustration of what's possible
package main

import (
    "context"
    "encoding/json"
    "io"
    "log"

    "github.com/fatih/color"
    "golang.org/x/exp/slog"
)

type PrettyHandlerOptions struct {
    SlogOpts slog.HandlerOptions
}

type PrettyHandler struct {
    opts PrettyHandlerOptions
    slog.Handler
    l *log.Logger
}

func (h *PrettyHandler) Handle(ctx context.Context, r slog.Record) error {
    level := r.Level.String() + ":"

    switch r.Level {
    case slog.LevelDebug:
        level = color.MagentaString(level)
    case slog.LevelInfo:
        level = color.BlueString(level)
    case slog.LevelWarn:
        level = color.YellowString(level)
    case slog.LevelError:
        level = color.RedString(level)
    }

    fields := make(map[string]interface{}, r.NumAttrs())
    r.Attrs(func(a slog.Attr) {
        fields[a.Key] = a.Value.Any()
    })

    b, err := json.MarshalIndent(fields, "", "  ")
    if err != nil {
        return err
    }

    timeStr := r.Time.Format("[15:05:05.000]")
    msg := color.CyanString(r.Message)

    h.l.Println(timeStr, level, msg, color.WhiteString(string(b)))

    return nil
}

func (opts PrettyHandlerOptions) NewPrettyHandler(
    out io.Writer,
) *PrettyHandler {
    h := &PrettyHandler{
        Handler: opts.SlogOpts.NewJSONHandler(out),
        l:       log.New(out, "", 0),
    }

    return h
}

当你在代码中像这样使用PrettyHandler时:

package main

import (
    "os"

    "golang.org/x/exp/slog"
)

func main() {
    opts := PrettyHandlerOptions{
        SlogOpts: slog.HandlerOptions{
            Level: slog.LevelDebug,
        },
    }
    handler := opts.NewPrettyHandler(os.Stdout)
    logger := slog.New(handler)
    logger.Debug(
        "executing database query",
        slog.String("query", "SELECT * FROM users"),
    )
    logger.Info("image upload successful", slog.String("image_id", "39ud88"))
    logger.Warn(
        "storage is 90% full",
        slog.String("available_space", "900.1 MB"),
    )
    logger.Error(
        "An error occurred while processing the request",
        slog.String("url", "https://example.com"),
    )
}

你将看到以下彩色输出:


LogValue接口

LogValuer接口允许任何Go类型定义自身转换为日志格式。通过实现如下所示的LogValue()方法来记录日志的值:

type LogValuer interface {
    LogValue() Value
}

你可以通过实现这个接口来定义各种类型的日志输出内容。下面看一个例子:

package main

import (
    "os"

    "golang.org/x/exp/slog"
)

// User does not implement `LogValuer`
type User struct {
    ID        string `json:"id"`
    FirstName string `json:"first_name"`
    LastName  string `json:"last_name"`
    Email     string `json:"email"`
    Password  string `json:"password"`
}

func main() {
    handler := slog.NewJSONHandler(os.Stdout)
    logger := slog.New(handler)

    u := &User{
        ID:        "user-12234",
        FirstName: "Jan",
        LastName:  "Doe",
        Email:     "jan@example.com",
        Password:  "pass-12334",
    }

    logger.Info("info", "user", u)
}

output:

{
  "time": "2023-02-26T22:11:30.080656774+01:00",
  "level": "INFO",
  "msg": "info",
  "user": {
    "id": "user-12234",
    "first_name": "Jan",
    "last_name": "Doe",
    "email": "jan@example.com",
    "password": "pass-12334"
  }
}

如果不实现LogValuer接口,整个User类型将被添加到如上所示的日志中。如果类型包含不应该出现在日志中的敏感字段(比如密码),这可能会产生问题,而且还会造成日志不必要地冗长。可以通过指定如何在日志中处理该类型来修复此问题。例如,你可以指定日志只记录User类型ID字段:

// implement the `LogValuer` interface
func (u *User) LogValue() slog.Value {
    return slog.StringValue(u.ID)
}

你现在将看到以下输出:

{
  "time": "2023-02-26T22:43:28.184363059+01:00",
  "level": "INFO",
  "msg": "info",
  "user": "user-12234"
}

你也可以像这样把属性分组在一起:

func (u *User) LogValue() slog.Value {
    return slog.GroupValue(
        slog.String("id", u.ID),
        slog.String("name", u.FirstName+" "+u.LastName),
    )
}

output:

{
  "time": "2023-03-15T14:44:24.223381036+01:00",
  "level": "INFO",
  "msg": "info",
  "user": {
    "id": "user-12234",
    "name": "Jan Doe"
  }
}

第三方日志库

上一篇 下一篇

猜你喜欢

热点阅读