package postLog import ( "fmt" "sync" "time" ) var ( loggerMutex sync.Mutex debugMode bool ) const ( DEBUG = iota INFO WARNING ERROR FATAL ) var levelNames = []string{"DEBUG", "INFO", "WARNING", "ERROR", "FATAL"} var levelColors = []int{34, 27, 220, 196, 124} func colorOut_256(s string, foreColor int) string { return fmt.Sprintf("\033[38;5;%dm%s\033[m", foreColor, s) } func getSystemTime() string { now := time.Now() return now.Format("2006-01-02 15:04:05.000") } // SetDebugMode sets the debug mode for the logger func SetDebugMode(debug bool) { loggerMutex.Lock() defer loggerMutex.Unlock() debugMode = debug } func PostLog(message string, level int) { timeNow := getSystemTime() idx := level if idx < 0 || idx >= len(levelNames) { idx = INFO // default to INFO } // Lock to make reading debug flag and all output atomic across threads loggerMutex.Lock() defer loggerMutex.Unlock() // Skip DEBUG when debug is off if idx == DEBUG && !debugMode { return } // Colored output levelDisplay := colorOut_256(levelNames[idx], levelColors[idx]) switch idx { case DEBUG: fmt.Printf("[%s - %s] %s\n", timeNow, levelDisplay, message) case INFO: fmt.Printf("[%s - %s] %s\n", timeNow, levelDisplay, message) case WARNING: fmt.Printf("[%s - %s] %s\n", timeNow, levelDisplay, message) case ERROR: fmt.Printf("[%s - %s] %s\n", timeNow, levelDisplay, message) case FATAL: fmt.Printf("[%s - %s] %s\n", timeNow, levelDisplay, message) } } // Helper functions for different log levels func Debug(message string) { PostLog(message, DEBUG) } func Info(message string) { PostLog(message, INFO) } func Warning(message string) { PostLog(message, WARNING) } func Error(message string) { PostLog(message, ERROR) } func Fatal(message string) { PostLog(message, FATAL) }