45 lines
853 B
Go
Raw Normal View History

2024-07-11 16:37:26 +08:00
package logger
import (
"fmt"
"github.com/loveuer/esgo2dump/log"
"github.com/loveuer/nf"
"github.com/loveuer/nf/nft/resp"
"strconv"
"time"
"ultone/internal/tool"
)
func New() nf.HandlerFunc {
return func(c *nf.Ctx) error {
var (
2024-07-17 23:05:23 +08:00
now = time.Now()
logFn func(msg string, data ...any)
ip = c.IP()
2024-07-11 16:37:26 +08:00
)
2024-07-17 23:05:23 +08:00
traceId := c.Context().Value(nf.TraceKey)
c.Locals(nf.TraceKey, traceId)
2024-07-11 16:37:26 +08:00
err := c.Next()
status, _ := strconv.Atoi(c.Writer.Header().Get(resp.RealStatusHeader))
duration := time.Since(now)
2024-07-17 21:31:51 +08:00
msg := fmt.Sprintf("%s | %15s | %d[%3d] | %s | %6s | %s", traceId, ip, c.StatusCode, status, tool.HumanDuration(duration.Nanoseconds()), c.Method(), c.Path())
2024-07-11 16:37:26 +08:00
switch {
case status >= 500:
logFn = log.Error
case status >= 400:
logFn = log.Warn
default:
logFn = log.Info
}
logFn(msg)
return err
}
}