fix(log): Trim trailing newlines to prevent blank log lines

This commit is contained in:
hkfires
2025-09-23 09:05:40 +08:00
parent 72ffeb73d3
commit 49232372a7

View File

@@ -48,8 +48,10 @@ 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")
var newLog string var newLog string
// Ensure message doesn't carry trailing newlines; formatter appends one.
msg := strings.TrimRight(entry.Message, "\r\n")
// Customize the log format to include timestamp, level, caller file/line, and message. // Customize the log format to include timestamp, level, caller file/line, and message.
newLog = fmt.Sprintf("[%s] [%s] [%s:%d] %s\n", timestamp, entry.Level, filepath.Base(entry.Caller.File), entry.Caller.Line, entry.Message) newLog = fmt.Sprintf("[%s] [%s] [%s:%d] %s\n", timestamp, entry.Level, filepath.Base(entry.Caller.File), entry.Caller.Line, msg)
b.WriteString(newLog) b.WriteString(newLog)
return b.Bytes(), nil return b.Bytes(), nil
@@ -84,6 +86,10 @@ func init() {
ginErrorWriter = log.StandardLogger().WriterLevel(log.ErrorLevel) ginErrorWriter = log.StandardLogger().WriterLevel(log.ErrorLevel)
gin.DefaultErrorWriter = ginErrorWriter gin.DefaultErrorWriter = ginErrorWriter
gin.DebugPrintFunc = func(format string, values ...interface{}) { gin.DebugPrintFunc = func(format string, values ...interface{}) {
// Trim trailing newlines from Gin's formatted messages to avoid blank lines.
// Gin's debug prints usually include a trailing "\n"; our formatter also appends one.
// Removing it here ensures a single newline per entry.
format = strings.TrimRight(format, "\r\n")
log.StandardLogger().Infof(format, values...) log.StandardLogger().Infof(format, values...)
} }
log.RegisterExitHandler(func() { log.RegisterExitHandler(func() {