| 1 | module log |
| 2 | |
| 3 | import term |
| 4 | |
| 5 | // Level defines the possible log levels, used by Log.set_level() |
| 6 | pub enum Level { |
| 7 | disabled = 0 // lowest level, disables everything else |
| 8 | fatal // disables error, warn, info and debug |
| 9 | error // disables warn, info and debug |
| 10 | warn // disables info and debug |
| 11 | info // disables debug |
| 12 | debug |
| 13 | } |
| 14 | |
| 15 | // LogTarget defines the possible log targets, that Log supports |
| 16 | pub enum LogTarget { |
| 17 | console |
| 18 | file |
| 19 | both |
| 20 | } |
| 21 | |
| 22 | // tag_to_console returns the tag for log level `l` as a colored string. |
| 23 | @[noinline] |
| 24 | fn tag_to_console(l Level, short_tag bool) string { |
| 25 | if short_tag { |
| 26 | return match l { |
| 27 | .disabled { ' ' } |
| 28 | .fatal { term.red('F') } |
| 29 | .error { term.red('E') } |
| 30 | .warn { term.yellow('W') } |
| 31 | .info { term.white('I') } |
| 32 | .debug { term.magenta('D') } |
| 33 | } |
| 34 | } else { |
| 35 | return match l { |
| 36 | .disabled { '' } |
| 37 | .fatal { term.red('FATAL') } |
| 38 | .error { term.red('ERROR') } |
| 39 | .warn { term.yellow('WARN ') } |
| 40 | .info { term.white('INFO ') } |
| 41 | .debug { term.magenta('DEBUG') } |
| 42 | } |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | // tag_to_file returns the tag for log level `l` as a string. |
| 47 | @[noinline] |
| 48 | fn tag_to_file(l Level, short_tag bool) string { |
| 49 | if short_tag { |
| 50 | return match l { |
| 51 | .disabled { ' ' } |
| 52 | .fatal { 'F' } |
| 53 | .error { 'E' } |
| 54 | .warn { 'W' } |
| 55 | .info { 'I' } |
| 56 | .debug { 'D' } |
| 57 | } |
| 58 | } else { |
| 59 | return match l { |
| 60 | .disabled { ' ' } |
| 61 | .fatal { 'FATAL' } |
| 62 | .error { 'ERROR' } |
| 63 | .warn { 'WARN ' } |
| 64 | .info { 'INFO ' } |
| 65 | .debug { 'DEBUG' } |
| 66 | } |
| 67 | } |
| 68 | } |
| 69 | |
| 70 | // level_from_tag returns the log level from the given string. |
| 71 | // It returns `none` when it does not find a match. |
| 72 | @[noinline] |
| 73 | pub fn level_from_tag(tag string) ?Level { |
| 74 | return match tag { |
| 75 | 'DISABLED', ' ' { Level.disabled } |
| 76 | 'FATAL', 'F' { Level.fatal } |
| 77 | 'ERROR', 'E' { Level.error } |
| 78 | 'WARN', 'W' { Level.warn } |
| 79 | 'INFO', 'I' { Level.info } |
| 80 | 'DEBUG', 'D' { Level.debug } |
| 81 | else { none } |
| 82 | } |
| 83 | } |
| 84 | |
| 85 | // target_from_label returns the log target from the given string. |
| 86 | // It returns `none` when it does not find a match. |
| 87 | @[noinline] |
| 88 | pub fn target_from_label(label string) ?LogTarget { |
| 89 | return match label { |
| 90 | 'console' { LogTarget.console } |
| 91 | 'file' { LogTarget.file } |
| 92 | 'both' { LogTarget.both } |
| 93 | else { none } |
| 94 | } |
| 95 | } |
| 96 | |