David K. Bainbridge | 528b318 | 2017-01-23 08:51:59 -0800 | [diff] [blame] | 1 | // Copyright 2016 Canonical Ltd. |
| 2 | // Licensed under the LGPLv3, see LICENCE file for details. |
| 3 | |
| 4 | package loggo |
| 5 | |
| 6 | import ( |
| 7 | "strings" |
| 8 | "sync/atomic" |
| 9 | ) |
| 10 | |
| 11 | // The severity levels. Higher values are more considered more |
| 12 | // important. |
| 13 | const ( |
| 14 | UNSPECIFIED Level = iota |
| 15 | TRACE |
| 16 | DEBUG |
| 17 | INFO |
| 18 | WARNING |
| 19 | ERROR |
| 20 | CRITICAL |
| 21 | ) |
| 22 | |
| 23 | // Level holds a severity level. |
| 24 | type Level uint32 |
| 25 | |
| 26 | // ParseLevel converts a string representation of a logging level to a |
| 27 | // Level. It returns the level and whether it was valid or not. |
| 28 | func ParseLevel(level string) (Level, bool) { |
| 29 | level = strings.ToUpper(level) |
| 30 | switch level { |
| 31 | case "UNSPECIFIED": |
| 32 | return UNSPECIFIED, true |
| 33 | case "TRACE": |
| 34 | return TRACE, true |
| 35 | case "DEBUG": |
| 36 | return DEBUG, true |
| 37 | case "INFO": |
| 38 | return INFO, true |
| 39 | case "WARN", "WARNING": |
| 40 | return WARNING, true |
| 41 | case "ERROR": |
| 42 | return ERROR, true |
| 43 | case "CRITICAL": |
| 44 | return CRITICAL, true |
| 45 | default: |
| 46 | return UNSPECIFIED, false |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | // String implements Stringer. |
| 51 | func (level Level) String() string { |
| 52 | switch level { |
| 53 | case UNSPECIFIED: |
| 54 | return "UNSPECIFIED" |
| 55 | case TRACE: |
| 56 | return "TRACE" |
| 57 | case DEBUG: |
| 58 | return "DEBUG" |
| 59 | case INFO: |
| 60 | return "INFO" |
| 61 | case WARNING: |
| 62 | return "WARNING" |
| 63 | case ERROR: |
| 64 | return "ERROR" |
| 65 | case CRITICAL: |
| 66 | return "CRITICAL" |
| 67 | default: |
| 68 | return "<unknown>" |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | // Short returns a five character string to use in |
| 73 | // aligned logging output. |
| 74 | func (level Level) Short() string { |
| 75 | switch level { |
| 76 | case TRACE: |
| 77 | return "TRACE" |
| 78 | case DEBUG: |
| 79 | return "DEBUG" |
| 80 | case INFO: |
| 81 | return "INFO " |
| 82 | case WARNING: |
| 83 | return "WARN " |
| 84 | case ERROR: |
| 85 | return "ERROR" |
| 86 | case CRITICAL: |
| 87 | return "CRITC" |
| 88 | default: |
| 89 | return " " |
| 90 | } |
| 91 | } |
| 92 | |
| 93 | // get atomically gets the value of the given level. |
| 94 | func (level *Level) get() Level { |
| 95 | return Level(atomic.LoadUint32((*uint32)(level))) |
| 96 | } |
| 97 | |
| 98 | // set atomically sets the value of the receiver |
| 99 | // to the given level. |
| 100 | func (level *Level) set(newLevel Level) { |
| 101 | atomic.StoreUint32((*uint32)(level), uint32(newLevel)) |
| 102 | } |