mirror of
				https://github.com/songquanpeng/one-api.git
				synced 2025-11-04 07:43:41 +08:00 
			
		
		
		
	feat: record request_id
This commit is contained in:
		@@ -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)
 | 
			
		||||
 
 | 
			
		||||
@@ -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)
 | 
			
		||||
 
 | 
			
		||||
		Reference in New Issue
	
	Block a user