src/hastyscribepkg/niftylogger.nim
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 |
import std/logging, std/strutils, std/terminal, std/exitprocs if isatty(stdin): addExitProc(resetAttributes) type NiftyLogger* = ref object of Logger proc logPrefix*(level: Level): tuple[msg: string, color: ForegroundColor] = case level: of lvlDebug: return ("---", fgMagenta) of lvlInfo: return ("(i)", fgCyan) of lvlNotice: return (" ", fgWhite) of lvlWarn: return ("(!)", fgYellow) of lvlError: return ("(!)", fgRed) of lvlFatal: return ("(x)", fgRed) else: return (" ", fgWhite) method log*(logger: NiftyLogger; level: Level; args: varargs[string, `$`]) = var f = stdout if level >= getLogFilter() and level >= logger.levelThreshold: if level >= lvlWarn: f = stderr let ln = substituteLog(logger.fmtStr, level, args) let prefix = level.logPrefix() f.setForegroundColor(prefix.color) f.write(prefix.msg) f.write(ln) resetAttributes() f.write("\n") if level in {lvlError, lvlFatal}: flushFile(f) proc newNiftyLogger*(levelThreshold = lvlAll; fmtStr = " "): NiftyLogger = new result result.fmtStr = fmtStr result.levelThreshold = levelThreshold proc getLogLevel*(): string = return LevelNames[getLogFilter()].toLowerAscii proc setLogLevel*(val: var string): string {.discardable.} = var lvl: Level case val: of "debug": lvl = lvlDebug of "info": lvl = lvlInfo of "notice": lvl = lvlNotice of "warn": lvl = lvlWarn of "error": lvl = lvlError of "fatal": lvl = lvlFatal of "none": lvl = lvlNone else: val = "warn" lvl = lvlWarn setLogFilter(lvl) return val |