feat: record request_id

This commit is contained in:
JustSong
2025-01-31 17:54:04 +08:00
parent 1fead8e7f7
commit d0402f9086
11 changed files with 96 additions and 55 deletions

View File

@@ -1,9 +1,8 @@
package helper
import (
"context"
"fmt"
"github.com/gin-gonic/gin"
"github.com/songquanpeng/one-api/common/random"
"html/template"
"log"
"net"
@@ -11,6 +10,10 @@ import (
"runtime"
"strconv"
"strings"
"github.com/gin-gonic/gin"
"github.com/songquanpeng/one-api/common/random"
)
func OpenBrowser(url string) {
@@ -106,6 +109,18 @@ func GenRequestID() string {
return GetTimeString() + random.GetRandomNumberString(8)
}
func SetRequestID(ctx context.Context, id string) context.Context {
return context.WithValue(ctx, RequestIdKey, id)
}
func GetRequestID(ctx context.Context) string {
rawRequestId := ctx.Value(RequestIdKey)
if rawRequestId == nil {
return ""
}
return rawRequestId.(string)
}
func GetResponseID(c *gin.Context) string {
logID := c.GetString(RequestIdKey)
return fmt.Sprintf("chatcmpl-%s", logID)

View File

@@ -113,16 +113,16 @@ func logHelper(ctx context.Context, level loggerLevel, msg string) {
if level == loggerINFO {
writer = gin.DefaultWriter
}
var logId string
var requestId string
if ctx != nil {
rawLogId := ctx.Value(helper.RequestIdKey)
if rawLogId != nil {
logId = fmt.Sprintf(" | %s", rawLogId.(string))
rawRequestId := helper.GetRequestID(ctx)
if rawRequestId != "" {
requestId = fmt.Sprintf(" | %s", rawRequestId)
}
}
lineInfo, funcName := getLineInfo()
now := time.Now()
_, _ = fmt.Fprintf(writer, "[%s] %v%s%s %s%s \n", level, now.Format("2006/01/02 - 15:04:05"), logId, lineInfo, funcName, msg)
_, _ = fmt.Fprintf(writer, "[%s] %v%s%s %s%s \n", level, now.Format("2006/01/02 - 15:04:05"), requestId, lineInfo, funcName, msg)
SetupLogger()
if level == loggerFatal {
os.Exit(1)