github.com/bshelton229/agent@v3.5.4+incompatible/logger/log.go (about) 1 package logger 2 3 import ( 4 "fmt" 5 "io" 6 "os" 7 "runtime" 8 "strings" 9 "sync" 10 "time" 11 12 "golang.org/x/crypto/ssh/terminal" 13 ) 14 15 const ( 16 nocolor = "0" 17 red = "31" 18 green = "1;32" 19 yellow = "33" 20 blue = "34" 21 gray = "1;30" 22 cyan = "1;36" 23 ) 24 25 var level = INFO 26 var colors = true 27 var mutex = sync.Mutex{} 28 29 func GetLevel() Level { 30 return level 31 } 32 33 func SetLevel(l Level) { 34 level = l 35 36 if level == DEBUG { 37 Debug("Debug mode enabled") 38 } 39 } 40 41 func SetColors(b bool) { 42 colors = b 43 } 44 45 func ColorsEnabled() bool { 46 if runtime.GOOS == "windows" { 47 // Boo, no colors on Windows. 48 return false 49 } else { 50 // Colors can only be shown if STDOUT is a terminal 51 if terminal.IsTerminal(int(os.Stdout.Fd())) { 52 return colors 53 } else { 54 return false 55 } 56 } 57 } 58 59 func OutputPipe() io.Writer { 60 // All logging, all the time, goes to STDERR 61 return os.Stderr 62 } 63 64 func Debug(format string, v ...interface{}) { 65 if level == DEBUG { 66 log(DEBUG, format, v...) 67 } 68 } 69 70 func Error(format string, v ...interface{}) { 71 log(ERROR, format, v...) 72 } 73 74 func Fatal(format string, v ...interface{}) { 75 log(FATAL, format, v...) 76 os.Exit(1) 77 } 78 79 func Notice(format string, v ...interface{}) { 80 log(NOTICE, format, v...) 81 } 82 83 func Info(format string, v ...interface{}) { 84 log(INFO, format, v...) 85 } 86 87 func Warn(format string, v ...interface{}) { 88 log(WARN, format, v...) 89 } 90 91 func log(l Level, format string, v ...interface{}) { 92 level := strings.ToUpper(l.String()) 93 message := fmt.Sprintf(format, v...) 94 now := time.Now().Format("2006-01-02 15:04:05") 95 line := "" 96 97 if ColorsEnabled() { 98 prefixColor := green 99 messageColor := nocolor 100 101 if l == DEBUG { 102 prefixColor = gray 103 messageColor = gray 104 } else if l == NOTICE { 105 prefixColor = cyan 106 } else if l == WARN { 107 prefixColor = yellow 108 } else if l == ERROR { 109 prefixColor = red 110 } else if l == FATAL { 111 prefixColor = red 112 messageColor = red 113 } 114 115 line = fmt.Sprintf("\x1b[%sm%s %-6s\x1b[0m \x1b[%sm%s\x1b[0m\n", prefixColor, now, level, messageColor, message) 116 } else { 117 line = fmt.Sprintf("%s %-6s %s\n", now, level, message) 118 } 119 120 // Make sure we're only outputing a line one at a time 121 mutex.Lock() 122 fmt.Fprint(OutputPipe(), line) 123 mutex.Unlock() 124 }