refactor(logging): standardize request id formatting and layout

This commit is contained in:
hkfires
2025-12-24 22:03:07 +08:00
parent 99238a4b59
commit 5ba325a8fc
2 changed files with 6 additions and 10 deletions

View File

@@ -76,12 +76,12 @@ func GinLogrusLogger() gin.HandlerFunc {
if requestID == "" { if requestID == "" {
requestID = "--------" requestID = "--------"
} }
logLine := fmt.Sprintf("%3d | %13v | %15s | %s | %-7s \"%s\"", statusCode, latency, clientIP, requestID, method, path) logLine := fmt.Sprintf("%3d | %13v | %15s | %-7s \"%s\"", statusCode, latency, clientIP, method, path)
if errorMessage != "" { if errorMessage != "" {
logLine = logLine + " | " + errorMessage logLine = logLine + " | " + errorMessage
} }
entry := log.NewEntry(log.StandardLogger()) entry := log.WithField("request_id", requestID)
switch { switch {
case statusCode >= http.StatusInternalServerError: case statusCode >= http.StatusInternalServerError:

View File

@@ -40,7 +40,7 @@ func (m *LogFormatter) Format(entry *log.Entry) ([]byte, error) {
timestamp := entry.Time.Format("2006-01-02 15:04:05") timestamp := entry.Time.Format("2006-01-02 15:04:05")
message := strings.TrimRight(entry.Message, "\r\n") message := strings.TrimRight(entry.Message, "\r\n")
reqID := "" reqID := "--------"
if id, ok := entry.Data["request_id"].(string); ok && id != "" { if id, ok := entry.Data["request_id"].(string); ok && id != "" {
reqID = id reqID = id
} }
@@ -52,14 +52,10 @@ func (m *LogFormatter) Format(entry *log.Entry) ([]byte, error) {
levelStr := fmt.Sprintf("%-5s", level) levelStr := fmt.Sprintf("%-5s", level)
var formatted string var formatted string
if reqID != "" && entry.Caller != nil { if entry.Caller != nil {
formatted = fmt.Sprintf("[%s] [%s] [%s:%d] | %s | %s\n", timestamp, levelStr, filepath.Base(entry.Caller.File), entry.Caller.Line, reqID, message) formatted = fmt.Sprintf("[%s] [%s] [%s] [%s:%d] %s\n", timestamp, reqID, levelStr, filepath.Base(entry.Caller.File), entry.Caller.Line, message)
} else if reqID != "" {
formatted = fmt.Sprintf("[%s] [%s] | %s | %s\n", timestamp, levelStr, reqID, message)
} else if entry.Caller != nil {
formatted = fmt.Sprintf("[%s] [%s] [%s:%d] %s\n", timestamp, levelStr, filepath.Base(entry.Caller.File), entry.Caller.Line, message)
} else { } else {
formatted = fmt.Sprintf("[%s] [%s] %s\n", timestamp, levelStr, message) formatted = fmt.Sprintf("[%s] [%s] [%s] %s\n", timestamp, reqID, levelStr, message)
} }
buffer.WriteString(formatted) buffer.WriteString(formatted)