good morning!!!!

Skip to content
Snippets Groups Projects
log.go 1.21 KiB
Newer Older
a's avatar
a committed
package middleware

import (
a's avatar
a committed
	"context"
a's avatar
a committed
	"time"

a's avatar
a committed
	"gfx.cafe/open/jrpc/pkg/codec"

	"log/slog"
a's avatar
a committed
)

a's avatar
a committed
// Key to use when setting the request ID.
type ctxKeyLogger int

// RequestIDKey is the key that holds the unique request ID in a request context.
const LoggerKey ctxKeyLogger = 76

a's avatar
a committed
func NewLogger(logger *slog.Logger) func(next codec.Handler) codec.Handler {
	return func(next codec.Handler) codec.Handler {
		fn := func(w codec.ResponseWriter, r *codec.Request) {
			start := time.Now()
			lg := logger.With(
				"remote", r.Remote(),
				"method", r.Method,
				"params", string(r.Msg().Params),
			)
			if id := GetReqID(r.Context()); id != "" {
				lg = logger.With(
					"req_id", id,
				)
			}
			next.ServeRPC(w, r.WithContext(context.WithValue(r.Context(), LoggerKey, lg)))
			lg = logger.With(
				"params", time.Since(start),
			)
			logger.LogAttrs(r.Context(), slog.LevelDebug, "RPC Request")
a's avatar
a committed
		}
a's avatar
a committed
		return codec.HandlerFunc(fn)
a's avatar
a committed
	}
}
a's avatar
a committed

a's avatar
a committed
func Logger(next codec.Handler) codec.Handler {
	lh := slog.Default()
	return NewLogger(lh)(next)
}

func GetLogger(ctx context.Context) *slog.Logger {
a's avatar
a committed
	if ctx == nil {
a's avatar
a committed
		return slog.Default()
a's avatar
a committed
	}
a's avatar
a committed
	if lgr, ok := ctx.Value(LoggerKey).(*slog.Logger); ok {
a's avatar
a committed
		return lgr
	}
a's avatar
a committed
	return slog.Default()
a's avatar
a committed
}