levels.go (1335B)
1 package level 2 3 import ( 4 "fmt" 5 "strings" 6 ) 7 8 // LEVEL defines a level of logging. 9 type LEVEL uint8 10 11 // Default levels of logging. 12 const ( 13 UNSET LEVEL = 0 14 PANIC LEVEL = 1 15 FATAL LEVEL = 50 16 ERROR LEVEL = 100 17 WARN LEVEL = 150 18 INFO LEVEL = 200 19 DEBUG LEVEL = 250 20 TRACE LEVEL = 254 21 ALL LEVEL = ^LEVEL(0) 22 ) 23 24 // CanLog returns whether an incoming log of 'lvl' can be logged against receiving level. 25 func (loglvl LEVEL) CanLog(lvl LEVEL) bool { 26 return loglvl > lvl 27 } 28 29 // Levels defines a mapping of log LEVELs to formatted level strings. 30 type Levels [int(ALL) + 1]string 31 32 // Default returns the default set of log levels. 33 func Default() Levels { 34 return Levels{ 35 TRACE: "TRACE", 36 DEBUG: "DEBUG", 37 INFO: "INFO", 38 WARN: "WARN", 39 ERROR: "ERROR", 40 FATAL: "FATAL", 41 PANIC: "PANIC", 42 } 43 } 44 45 // Get fetches the level string for the provided value. 46 func (l Levels) Get(lvl LEVEL) string { 47 return l[int(lvl)] 48 } 49 50 // Parse will attempt to decode a LEVEL from given string, checking (case insensitive) against strings in Levels. 51 func (l Levels) Parse(s string) (LEVEL, error) { 52 // Ensure consistent casing 53 s = strings.ToUpper(s) 54 55 for lvl := LEVEL(0); int(lvl) < len(l); lvl++ { 56 // Compare to eqach known level 57 if strings.ToUpper(l[lvl]) == s { 58 return lvl, nil 59 } 60 } 61 62 return 0, fmt.Errorf("unrecognized log level: %s", s) 63 }