Format renders a single log entry with custom formatting.
(entry *log.Entry)
| 41 | |
| 42 | // Format renders a single log entry with custom formatting. |
| 43 | func (m *LogFormatter) Format(entry *log.Entry) ([]byte, error) { |
| 44 | var buffer *bytes.Buffer |
| 45 | if entry.Buffer != nil { |
| 46 | buffer = entry.Buffer |
| 47 | } else { |
| 48 | buffer = &bytes.Buffer{} |
| 49 | } |
| 50 | |
| 51 | timestamp := entry.Time.Format("2006-01-02 15:04:05") |
| 52 | message := strings.TrimRight(entry.Message, "\r\n") |
| 53 | |
| 54 | reqID := "--------" |
| 55 | if id, ok := entry.Data["request_id"].(string); ok && id != "" { |
| 56 | reqID = id |
| 57 | } |
| 58 | |
| 59 | level := entry.Level.String() |
| 60 | if level == "warning" { |
| 61 | level = "warn" |
| 62 | } |
| 63 | levelStr := fmt.Sprintf("%-5s", level) |
| 64 | |
| 65 | // Build fields string (only print fields in logFieldOrder) |
| 66 | var fieldsStr string |
| 67 | if len(entry.Data) > 0 { |
| 68 | var fields []string |
| 69 | for _, k := range logFieldOrder { |
| 70 | if v, ok := entry.Data[k]; ok { |
| 71 | fields = append(fields, fmt.Sprintf("%s=%v", k, v)) |
| 72 | } |
| 73 | } |
| 74 | if pluginID, ok := entry.Data["plugin_id"]; ok && strings.TrimSpace(fmt.Sprint(pluginID)) != "" { |
| 75 | for _, k := range pluginPathFieldOrder { |
| 76 | if v, ok := entry.Data[k]; ok { |
| 77 | fields = append(fields, fmt.Sprintf("%s=%v", k, v)) |
| 78 | } |
| 79 | } |
| 80 | } |
| 81 | if len(fields) > 0 { |
| 82 | fieldsStr = " " + strings.Join(fields, " ") |
| 83 | } |
| 84 | } |
| 85 | |
| 86 | var formatted string |
| 87 | if entry.Caller != nil { |
| 88 | formatted = fmt.Sprintf("[%s] [%s] [%s] [%s:%d] %s%s\n", timestamp, reqID, levelStr, filepath.Base(entry.Caller.File), entry.Caller.Line, message, fieldsStr) |
| 89 | } else { |
| 90 | formatted = fmt.Sprintf("[%s] [%s] [%s] %s%s\n", timestamp, reqID, levelStr, message, fieldsStr) |
| 91 | } |
| 92 | buffer.WriteString(formatted) |
| 93 | |
| 94 | return buffer.Bytes(), nil |
| 95 | } |
| 96 | |
| 97 | // SetupBaseLogger configures the shared logrus instance and Gin writers. |
| 98 | // It is safe to call multiple times; initialization happens only once. |