go logrus输出trace_id

 

go get github.com/google/uuid
go get github.com/sirupsen/logrus

方式1:非并发场景使用hook 

package main

import (
	"github.com/sirupsen/logrus"
)

type TraceIdHook struct {
	TraceId string
}

func NewTraceIdHook(traceId string) logrus.Hook {
	hook := TraceIdHook{
		TraceId: traceId,
	}
	return &hook
}

func (hook *TraceIdHook) Fire(entry *logrus.Entry) error {
	entry.Data["trace_id"] = hook.TraceId
	return nil
}

func (hook *TraceIdHook) Levels() []logrus.Level {
	return logrus.AllLevels
}

package main

import (
	"fmt"
	"io"
	"os"
	"path/filepath"
	"runtime"

	"github.com/google/uuid"
	"github.com/sirupsen/logrus"
)

func init() {
	logrus.SetReportCaller(true)
	logrus.SetFormatter(
		&logrus.JSONFormatter{
			TimestampFormat: "2006-01-02 15:04:05",
			CallerPrettyfier: func(f *runtime.Frame) (function string, file string) {
				return "", fmt.Sprintf("%s:%d", filepath.Base(f.File), f.Line)
			},
		},
	)

	logrus.SetOutput(io.MultiWriter(os.Stdout))
}

func main() {
	logrus.AddHook(NewTraceIdHook(uuid.NewString()))
	logrus.Info("a")
	logrus.Info("b")
}

方式2:并发场景使用传参(推荐)

logrus.WithField("trace_id", traceId).Infof(msg)

 

posted on 2025-01-28 15:00  王景迁  阅读(48)  评论(0)    收藏  举报

导航