good morning!!!!

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

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

	"gfx.cafe/open/jrpc"
a's avatar
a committed
	"tuxpa.in/a/zlog"
a's avatar
a committed
	"tuxpa.in/a/zlog/log"
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 Logger(next jrpc.Handler) jrpc.Handler {
	fn := func(w jrpc.ResponseWriter, r *jrpc.Request) {
		start := time.Now()
a's avatar
a committed
		l := log.Trace().
			Str("id", GetReqID(r.Context())).
a's avatar
a committed
			Str("remote", r.Remote()).
jjohnstondev's avatar
jjohnstondev committed
			Str("method", r.Method).
a's avatar
a committed
			Str("params", string(r.Msg().Params))
		next.ServeRPC(w, r.WithContext(context.WithValue(r.Context(), LoggerKey, l)))
		l = l.Stringer("dur", time.Since(start))
		l.Msg("RPC Request")
a's avatar
a committed
	}
	return jrpc.HandlerFunc(fn)
}
a's avatar
a committed

func GetLogger(ctx context.Context) *zlog.Event {
	if ctx == nil {
		return log.Debug()
	}
	if lgr, ok := ctx.Value(LoggerKey).(*zlog.Event); ok {
		return lgr
	}
	return log.Debug()
}