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:
push:
branches:
- 'master'
- 'release/nfctl/*'
env:
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)
request.WithContext(c)
ctx := &Ctx{
lock: sync.Mutex{},
Request: request,
Request: request.WithContext(c),
path: request.URL.Path,
method: request.Method,
StatusCode: 200,
@ -75,6 +74,7 @@ func newContext(app *App, writer http.ResponseWriter, request *http.Request) *Ct
}
ctx.Writer = &ctx.writermem
ctx.writermem.Header().Set(TraceKey, traceId)
return ctx
}

View File

@ -2,11 +2,9 @@ package nf
import (
"fmt"
"github.com/google/uuid"
"github.com/loveuer/nf/nft/log"
"os"
"runtime/debug"
"strings"
"time"
)
@ -29,33 +27,19 @@ func NewRecover(enableStackTrace bool) HandlerFunc {
}
}
func NewLogger(traceHeader ...string) HandlerFunc {
Header := "X-Trace-ID"
if len(traceHeader) > 0 && traceHeader[0] != "" {
Header = traceHeader[0]
}
func NewLogger() HandlerFunc {
return func(c *Ctx) error {
var (
now = time.Now()
trace = c.Get(Header)
logFn func(msg string, data ...any)
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()
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 {
case c.StatusCode >= 500: