chore: X-Trace-Id

fix req context trace id; default logger with trace-id

ci: fix nfctl run
This commit is contained in:
loveuer 2024-07-17 23:00:45 +08:00
parent e4a6228b0a
commit 40e8a3e613
3 changed files with 5 additions and 21 deletions

View File

@ -2,7 +2,7 @@ name: Auto Build
on: on:
push: push:
branches: branches:
- 'master' - 'release/nfctl/*'
env: env:
RELEASE_VERSION: v24.07.14-r3 RELEASE_VERSION: v24.07.14-r3

4
ctx.go
View File

@ -51,11 +51,10 @@ func newContext(app *App, writer http.ResponseWriter, request *http.Request) *Ct
} }
c := context.WithValue(request.Context(), TraceKey, traceId) c := context.WithValue(request.Context(), TraceKey, traceId)
request.WithContext(c)
ctx := &Ctx{ ctx := &Ctx{
lock: sync.Mutex{}, lock: sync.Mutex{},
Request: request, Request: request.WithContext(c),
path: request.URL.Path, path: request.URL.Path,
method: request.Method, method: request.Method,
StatusCode: 200, StatusCode: 200,
@ -75,6 +74,7 @@ func newContext(app *App, writer http.ResponseWriter, request *http.Request) *Ct
} }
ctx.Writer = &ctx.writermem ctx.Writer = &ctx.writermem
ctx.writermem.Header().Set(TraceKey, traceId)
return ctx return ctx
} }

View File

@ -2,11 +2,9 @@ package nf
import ( import (
"fmt" "fmt"
"github.com/google/uuid"
"github.com/loveuer/nf/nft/log" "github.com/loveuer/nf/nft/log"
"os" "os"
"runtime/debug" "runtime/debug"
"strings"
"time" "time"
) )
@ -29,33 +27,19 @@ func NewRecover(enableStackTrace bool) HandlerFunc {
} }
} }
func NewLogger(traceHeader ...string) HandlerFunc { func NewLogger() HandlerFunc {
Header := "X-Trace-ID"
if len(traceHeader) > 0 && traceHeader[0] != "" {
Header = traceHeader[0]
}
return func(c *Ctx) error { return func(c *Ctx) error {
var ( var (
now = time.Now() now = time.Now()
trace = c.Get(Header)
logFn func(msg string, data ...any) logFn func(msg string, data ...any)
ip = c.IP() ip = c.IP()
) )
if trace == "" {
trace = uuid.Must(uuid.NewV7()).String()
}
c.SetHeader(Header, trace)
traces := strings.Split(trace, "-")
shortTrace := traces[len(traces)-1]
err := c.Next() err := c.Next()
duration := time.Since(now) duration := time.Since(now)
msg := fmt.Sprintf("NF | %s | %15s | %3d | %s | %6s | %s", shortTrace, ip, c.StatusCode, HumanDuration(duration.Nanoseconds()), c.Method(), c.Path()) msg := fmt.Sprintf("NF | %v | %15s | %3d | %s | %6s | %s", c.Context().Value(TraceKey), ip, c.StatusCode, HumanDuration(duration.Nanoseconds()), c.Method(), c.Path())
switch { switch {
case c.StatusCode >= 500: case c.StatusCode >= 500: