From a9c60a3698c6b4afb292fca01625ff9cc1481b3f Mon Sep 17 00:00:00 2001 From: PhatPhuckDave Date: Thu, 27 Mar 2025 19:26:14 +0100 Subject: [PATCH] Neatly align log columns --- cmd/log_format_test/main.go | 27 +++++++++++++++++++++++++++ logger/logger.go | 19 +++++++++++++------ 2 files changed, 40 insertions(+), 6 deletions(-) create mode 100644 cmd/log_format_test/main.go diff --git a/cmd/log_format_test/main.go b/cmd/log_format_test/main.go new file mode 100644 index 0000000..370a5d0 --- /dev/null +++ b/cmd/log_format_test/main.go @@ -0,0 +1,27 @@ +package main + +import ( + "modify/logger" + "time" +) + +func main() { + // Initialize logger with DEBUG level + logger.Init(logger.LevelDebug) + + // Test different log levels + logger.Info("This is an info message") + logger.Debug("This is a debug message") + logger.Warning("This is a warning message") + logger.Error("This is an error message") + logger.Trace("This is a trace message (not visible at DEBUG level)") + + // Test with a goroutine + logger.SafeGo(func() { + time.Sleep(10 * time.Millisecond) + logger.Info("Message from goroutine") + }) + + // Wait for goroutine to complete + time.Sleep(20 * time.Millisecond) +} diff --git a/logger/logger.go b/logger/logger.go index e59489b..b36d88a 100644 --- a/logger/logger.go +++ b/logger/logger.go @@ -8,6 +8,7 @@ import ( "os" "path/filepath" "runtime" + "strconv" "strings" "sync" "time" @@ -269,9 +270,10 @@ func (l *Logger) formatMessage(level LogLevel, format string, args ...interface{ if l.flag&log.Lshortfile != 0 { file = filepath.Base(file) } - caller = fmt.Sprintf("%s:%d ", file, line) + caller = fmt.Sprintf("%-25s ", file+":"+strconv.Itoa(line)) } + // Format the timestamp with fixed width var timeStr string if l.flag&(log.Ldate|log.Ltime|log.Lmicroseconds) != 0 { t := time.Now() @@ -283,19 +285,24 @@ func (l *Logger) formatMessage(level LogLevel, format string, args ...interface{ if l.flag&log.Lmicroseconds != 0 { timeStr += fmt.Sprintf(".%06d", t.Nanosecond()/1000) } - timeStr += " " } + timeStr = fmt.Sprintf("%-15s ", timeStr) } - // Add goroutine ID if enabled + // Add goroutine ID if enabled, with fixed width var goroutineStr string if l.showGoroutine { goroutineID := GetGoroutineID() - goroutineStr = fmt.Sprintf("[g:%s] ", goroutineID) + goroutineStr = fmt.Sprintf("[g:%-4s] ", goroutineID) } - return fmt.Sprintf("%s%s%s%s%s[%s%s%s]%s %s\n", - l.prefix, timeStr, caller, goroutineStr, levelColor, levelNames[level], resetColor, fields, resetColor, msg) + // Create a colored level indicator with both brackets colored + levelStr := fmt.Sprintf("%s[%s]%s", levelColor, levelNames[level], levelColor) + // Add a space after the level and before the reset color + levelColumn := fmt.Sprintf("%s %s", levelStr, resetColor) + + return fmt.Sprintf("%s%s%s%s%s%s%s\n", + l.prefix, timeStr, caller, goroutineStr, levelColumn, msg, fields) } // log logs a message at the specified level