diff --git a/main.go b/main.go index a2f6367..03449d1 100644 --- a/main.go +++ b/main.go @@ -1,4 +1,5 @@ -package cylogger +// package cylogger +package main import ( "bytes" @@ -49,19 +50,19 @@ var levelNames = map[LogLevel]string{ } var levelColors = map[LogLevel]string{ - LevelError: "\033[1;31m", // Bold Red - LevelWarning: "\033[1;33m", // Bold Yellow - LevelInfo: "\033[1;32m", // Bold Green - LevelDebug: "\033[1;36m", // Bold Cyan - LevelTrace: "\033[1;35m", // Bold Magenta - LevelLua: "\033[1;34m", // Bold Blue - LevelPrefix: "\033[0;90m", // Regular Dark Grey + LevelError: BRed, + LevelWarning: BYellow, + LevelInfo: BGreen, + LevelDebug: BCyan, + LevelTrace: BPurple, + LevelLua: BBlue, + LevelPrefix: BIBlack, } // ANSI Background Colors var levelBackgroundColors = map[LogLevel]string{ - LevelError: "\033[41m", // Red Background - LevelWarning: "\033[43m", // Yellow Background + LevelError: On_IRed, + LevelWarning: On_IYellow, } // ANSI Foreground Colors (adjusting for readability on backgrounds) @@ -318,56 +319,54 @@ func (l *Logger) formatMessage(level LogLevel, format string, args ...interface{ fields = " " + strings.Join(pairs, " ") } - var levelColor, bgColor, msgFgColor, resetColor string - useBgColor := false // Flag to indicate if background color should be used + var levelColor, originalBgColor, resetColor, tagFgColor, tagBgColor, messageFgColor, messageBgColor string + useSpecialFormatting := false // Flag for ERROR/WARNING levels if l.useColors { resetColor = ResetColor - levelColor = levelColors[level] // Color for the level tag text ONLY + levelColor = levelColors[level] // Base color for the level text (e.g., BRed, BYellow) - if bg, ok := levelBackgroundColors[level]; ok { // Check if this level has a background color defined (ERROR/WARNING) - bgColor = bg - msgFgColor = FgWhiteBold // Use bold white for the message part on colored background - useBgColor = true + if bg, ok := levelBackgroundColors[level]; ok { // Check if ERROR or WARNING has a background color defined + useSpecialFormatting = true + originalBgColor = bg // Store original background (e.g., On_IRed, On_IYellow) + tagFgColor = levelColor // Use original level color for tag text (BRed/BYellow) + tagBgColor = On_White // Use White background FOR THE TAG + messageFgColor = FgWhiteBold // Use Bold White text FOR THE MESSAGE PART + messageBgColor = originalBgColor // Use original background FOR THE MESSAGE PART } else { - // For other levels, message part uses default terminal color. - // msgFgColor remains empty, bgColor remains empty. - // levelColor is still needed for the tag below. + // For other levels (INFO, DEBUG, etc.) + tagFgColor = levelColor // Just the standard foreground color for the tag text + // tagBgColor, messageFgColor, messageBgColor remain empty (use terminal defaults) } } var caller string if l.flag&log.Lshortfile != 0 || l.flag&log.Llongfile != 0 { - // Find the actual caller by scanning up the stack - // until we find a function outside the logger package var file string var line int var ok bool - // Start at a reasonable depth and scan up to 10 frames for depth := 4; depth < 15; depth++ { _, file, line, ok = runtime.Caller(depth) if !ok { break } - - // If the caller is not in the logger package, we found our caller - if !strings.Contains(file, "logger/logger.go") { + // Check if the caller is within this logger package itself + if !strings.Contains(file, "main.go") && !strings.Contains(file, "colors.go") { break } } - if !ok { file = "???" line = 0 } - if l.flag&log.Lshortfile != 0 { file = filepath.Base(file) } + // Caller string - no background color applied here caller = fmt.Sprintf("%-25s ", file+":"+strconv.Itoa(line)) } - // Format the timestamp with fixed width + // Format the timestamp with fixed width - no background color applied here var timeStr string if l.flag&(log.Ldate|log.Ltime|log.Lmicroseconds) != 0 { t := time.Now() @@ -383,41 +382,75 @@ func (l *Logger) formatMessage(level LogLevel, format string, args ...interface{ timeStr = fmt.Sprintf("%-15s ", timeStr) } - // Add goroutine ID if enabled, with fixed width + // Add goroutine ID if enabled, with fixed width - no background color applied here var goroutineStr string if l.showGoroutine { goroutineID := GetGoroutineID() goroutineStr = fmt.Sprintf("[g:%-4s] ", goroutineID) } - // Create a colored level indicator - color only the level name text, reset locally - levelStr := fmt.Sprintf("%s%s%s", levelColor, levelNames[level], resetColor) - levelColumn := fmt.Sprintf("%-20s", levelStr) // Pad the tag + // --- Level Tag Formatting and Padding --- + levelStr := levelNames[level] + visibleTagContent := fmt.Sprintf("[%s]", levelStr) + visibleTagLen := len(visibleTagContent) + paddingWidth := 10 // Target width for the level column (tag + padding) + numSpaces := paddingWidth - visibleTagLen + if numSpaces < 0 { + numSpaces = 1 // Ensure at least one space + } + padding := strings.Repeat(" ", numSpaces) + var levelTagFormatted string + if useSpecialFormatting { + // ERROR/WARNING: Tag has specific background and foreground + levelTagFormatted = fmt.Sprintf("%s%s%s%s", tagBgColor, tagFgColor, visibleTagContent, resetColor) + } else { + // Other levels: Tag has standard foreground color only + levelTagFormatted = fmt.Sprintf("%s%s%s", tagFgColor, visibleTagContent, resetColor) + } + levelColumn := levelTagFormatted + padding // Combine formatted tag and padding + + // --- User Prefix Formatting (part of message content for coloring purposes) --- userPrefixStr := "" if l.userPrefix != "" { - // Use default foreground color for prefix (dark grey), reset locally - prefixColor := levelColors[LevelPrefix] - userPrefixStr = fmt.Sprintf("%s[%s]%s ", prefixColor, l.userPrefix, resetColor) + // Format the string part here, colors applied later if needed + userPrefixStr = fmt.Sprintf("[%s] ", l.userPrefix) } - // Build the prefix part (timestamp, caller, goroutine, level tag, user prefix) - // These parts will use default terminal colors or their specifically set colors (like level tag) - prefixPart := fmt.Sprintf("%s%s%s%s%s%s", - l.prefix, timeStr, caller, goroutineStr, levelColumn, userPrefixStr) + // --- Message Content --- + messageContent := fmt.Sprintf("%s%s", msg, fields) - // Build the message part - messagePart := fmt.Sprintf("%s%s", msg, fields) + // --- Assemble Final String --- + var finalMsg strings.Builder - // Combine prefix and message, applying background/foreground ONLY to the message part - if useBgColor { - // Apply background and specific foreground ONLY to the message part - return fmt.Sprintf("%s%s%s%s%s", prefixPart, bgColor, msgFgColor, messagePart, resetColor) + // Part 1: Timestamp, Caller, Goroutine ID (always default colors) + finalMsg.WriteString(l.prefix) + finalMsg.WriteString(timeStr) + finalMsg.WriteString(caller) + finalMsg.WriteString(goroutineStr) + + // Part 2: Level Column (already formatted with tag colors and padding) + finalMsg.WriteString(levelColumn) + + // Part 3: User Prefix + Message Content (apply special formatting if needed) + if useSpecialFormatting { + // ERROR/WARNING: Apply message background and foreground to User Prefix + Message + finalMsg.WriteString(messageBgColor) + finalMsg.WriteString(messageFgColor) + finalMsg.WriteString(userPrefixStr) // Write user prefix inside the colored block + finalMsg.WriteString(messageContent) + finalMsg.WriteString(resetColor) // Reset after message } else { - // For non-ERROR/WARNING, just combine prefix (with its colored tag) and the uncolored message part. - // No additional color codes needed here for the message itself. - return fmt.Sprintf("%s%s", prefixPart, messagePart) + // Other levels: User Prefix and Message content use default colors + // Apply specific color to user prefix if it exists + if l.userPrefix != "" { + prefixColor := levelColors[LevelPrefix] + finalMsg.WriteString(fmt.Sprintf("%s%s%s", prefixColor, userPrefixStr, resetColor)) + } // No else needed, if userPrefix is empty, userPrefixStr is "" anyway + finalMsg.WriteString(messageContent) // Append message with default colors } + + return finalMsg.String() } // log logs a message at the specified level @@ -573,3 +606,42 @@ func ShowGoroutine() bool { } return Default.ShowGoroutine() } + +func main() { + Init(LevelDebug) + + // Test basic logging + Debug("This is a debug message") + Info("This is an info message") + Warning("This is a warning message") + Error("This is an error message") + + // Test logging with fields + logger := WithField("user", "testuser") + logger.Info("User logged in") + + // Test logging with multiple fields + fields := map[string]interface{}{ + "user": "testuser", + "role": "admin", + "id": 12345, + } + WithFields(fields).Info("User details") + + // Test error logging with fields + WithField("error", "connection failed").Error("Database error") + + logger.WithPrefix("CUSTOM").Info("This is a message with a custom prefix") + + // Test goroutine ID display + SetShowGoroutine(true) + Info("This message should show goroutine ID") + + // Test different log levels + SetLevel(LevelInfo) + Debug("This debug message should not appear") + Info("This info message should appear") + + // Test with custom prefix + WithField("prefix", "custom").Info("Message with custom prefix") +} diff --git a/safe.go b/safe.go index c45827b..55a9f1c 100644 --- a/safe.go +++ b/safe.go @@ -1,4 +1,4 @@ -package cylogger +package main import ( "fmt"