Rework coloring a little

Inspired by synclib
This commit is contained in:
2025-04-22 10:16:35 +02:00
parent 93557356e9
commit 04f9b0db6e
2 changed files with 122 additions and 50 deletions

170
main.go
View File

@@ -1,4 +1,5 @@
package cylogger // package cylogger
package main
import ( import (
"bytes" "bytes"
@@ -49,19 +50,19 @@ var levelNames = map[LogLevel]string{
} }
var levelColors = map[LogLevel]string{ var levelColors = map[LogLevel]string{
LevelError: "\033[1;31m", // Bold Red LevelError: BRed,
LevelWarning: "\033[1;33m", // Bold Yellow LevelWarning: BYellow,
LevelInfo: "\033[1;32m", // Bold Green LevelInfo: BGreen,
LevelDebug: "\033[1;36m", // Bold Cyan LevelDebug: BCyan,
LevelTrace: "\033[1;35m", // Bold Magenta LevelTrace: BPurple,
LevelLua: "\033[1;34m", // Bold Blue LevelLua: BBlue,
LevelPrefix: "\033[0;90m", // Regular Dark Grey LevelPrefix: BIBlack,
} }
// ANSI Background Colors // ANSI Background Colors
var levelBackgroundColors = map[LogLevel]string{ var levelBackgroundColors = map[LogLevel]string{
LevelError: "\033[41m", // Red Background LevelError: On_IRed,
LevelWarning: "\033[43m", // Yellow Background LevelWarning: On_IYellow,
} }
// ANSI Foreground Colors (adjusting for readability on backgrounds) // 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, " ") fields = " " + strings.Join(pairs, " ")
} }
var levelColor, bgColor, msgFgColor, resetColor string var levelColor, originalBgColor, resetColor, tagFgColor, tagBgColor, messageFgColor, messageBgColor string
useBgColor := false // Flag to indicate if background color should be used useSpecialFormatting := false // Flag for ERROR/WARNING levels
if l.useColors { if l.useColors {
resetColor = ResetColor 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) if bg, ok := levelBackgroundColors[level]; ok { // Check if ERROR or WARNING has a background color defined
bgColor = bg useSpecialFormatting = true
msgFgColor = FgWhiteBold // Use bold white for the message part on colored background originalBgColor = bg // Store original background (e.g., On_IRed, On_IYellow)
useBgColor = true 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 { } else {
// For other levels, message part uses default terminal color. // For other levels (INFO, DEBUG, etc.)
// msgFgColor remains empty, bgColor remains empty. tagFgColor = levelColor // Just the standard foreground color for the tag text
// levelColor is still needed for the tag below. // tagBgColor, messageFgColor, messageBgColor remain empty (use terminal defaults)
} }
} }
var caller string var caller string
if l.flag&log.Lshortfile != 0 || l.flag&log.Llongfile != 0 { 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 file string
var line int var line int
var ok bool var ok bool
// Start at a reasonable depth and scan up to 10 frames // Start at a reasonable depth and scan up to 10 frames
for depth := 4; depth < 15; depth++ { for depth := 4; depth < 15; depth++ {
_, file, line, ok = runtime.Caller(depth) _, file, line, ok = runtime.Caller(depth)
if !ok { if !ok {
break break
} }
// Check if the caller is within this logger package itself
// If the caller is not in the logger package, we found our caller if !strings.Contains(file, "main.go") && !strings.Contains(file, "colors.go") {
if !strings.Contains(file, "logger/logger.go") {
break break
} }
} }
if !ok { if !ok {
file = "???" file = "???"
line = 0 line = 0
} }
if l.flag&log.Lshortfile != 0 { if l.flag&log.Lshortfile != 0 {
file = filepath.Base(file) file = filepath.Base(file)
} }
// Caller string - no background color applied here
caller = fmt.Sprintf("%-25s ", file+":"+strconv.Itoa(line)) 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 var timeStr string
if l.flag&(log.Ldate|log.Ltime|log.Lmicroseconds) != 0 { if l.flag&(log.Ldate|log.Ltime|log.Lmicroseconds) != 0 {
t := time.Now() t := time.Now()
@@ -383,41 +382,75 @@ func (l *Logger) formatMessage(level LogLevel, format string, args ...interface{
timeStr = fmt.Sprintf("%-15s ", timeStr) 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 var goroutineStr string
if l.showGoroutine { if l.showGoroutine {
goroutineID := GetGoroutineID() goroutineID := GetGoroutineID()
goroutineStr = fmt.Sprintf("[g:%-4s] ", goroutineID) goroutineStr = fmt.Sprintf("[g:%-4s] ", goroutineID)
} }
// Create a colored level indicator - color only the level name text, reset locally // --- Level Tag Formatting and Padding ---
levelStr := fmt.Sprintf("%s%s%s", levelColor, levelNames[level], resetColor) levelStr := levelNames[level]
levelColumn := fmt.Sprintf("%-20s", levelStr) // Pad the tag 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 := "" userPrefixStr := ""
if l.userPrefix != "" { if l.userPrefix != "" {
// Use default foreground color for prefix (dark grey), reset locally // Format the string part here, colors applied later if needed
prefixColor := levelColors[LevelPrefix] userPrefixStr = fmt.Sprintf("[%s] ", l.userPrefix)
userPrefixStr = fmt.Sprintf("%s[%s]%s ", prefixColor, l.userPrefix, resetColor)
} }
// Build the prefix part (timestamp, caller, goroutine, level tag, user prefix) // --- Message Content ---
// These parts will use default terminal colors or their specifically set colors (like level tag) messageContent := fmt.Sprintf("%s%s", msg, fields)
prefixPart := fmt.Sprintf("%s%s%s%s%s%s",
l.prefix, timeStr, caller, goroutineStr, levelColumn, userPrefixStr)
// Build the message part // --- Assemble Final String ---
messagePart := fmt.Sprintf("%s%s", msg, fields) var finalMsg strings.Builder
// Combine prefix and message, applying background/foreground ONLY to the message part // Part 1: Timestamp, Caller, Goroutine ID (always default colors)
if useBgColor { finalMsg.WriteString(l.prefix)
// Apply background and specific foreground ONLY to the message part finalMsg.WriteString(timeStr)
return fmt.Sprintf("%s%s%s%s%s", prefixPart, bgColor, msgFgColor, messagePart, resetColor) 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 { } else {
// For non-ERROR/WARNING, just combine prefix (with its colored tag) and the uncolored message part. // Other levels: User Prefix and Message content use default colors
// No additional color codes needed here for the message itself. // Apply specific color to user prefix if it exists
return fmt.Sprintf("%s%s", prefixPart, messagePart) 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 // log logs a message at the specified level
@@ -573,3 +606,42 @@ func ShowGoroutine() bool {
} }
return Default.ShowGoroutine() 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")
}

View File

@@ -1,4 +1,4 @@
package cylogger package main
import ( import (
"fmt" "fmt"