all repos — min @ ca018c34568d8abae090a61bfc43ca37e3ddc46d

A small but practical concatenative programming language.

minpkg/core/minilogger.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
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
import
  strutils

type
  Level* = enum lvlAll, lvlDebug, lvlInfo, lvlNotice, lvlWarn, lvlError, lvlFatal, lvlNone
  
const
  LevelNames: array[Level, string] = [ "DEBUG", "DEBUG", "INFO", "NOTICE", "WARN", "ERROR", "FATAL", "NONE"]

var LOGLEVEL* {.threadvar.}: Level
LOGLEVEL = lvlNotice

proc logPrefix(level: Level): string =
  case level:
    of lvlDebug:
      return ("---")
    of lvlInfo:
      return ("(i)")
    of lvlNotice:
      return ("   ")
    of lvlWarn:
      return ("(!)")
    of lvlError:
      return ("(!)")
    of lvlFatal:
      return ("(x)")
    else:
      return ("   ")

proc log*(level: Level; args: varargs[string, `$`]) =
  var f = stdout
  if level >= LOGLEVEL:
    if level >= lvlWarn: 
      f = stderr
    let prefix = level.logPrefix()
    f.write(prefix&" ")
    f.write(args.join(" "))
    f.write("\n")
    if level in {lvlError, lvlFatal}: flushFile(f)

proc fatal*(args: varargs[string, `$`]) =
    log(lvlFatal, args)

proc error*(args: varargs[string, `$`]) =
    log(lvlError, args)

proc warn*(args: varargs[string, `$`]) =
    log(lvlWarn, args)

proc notice*(args: varargs[string, `$`]) =
    log(lvlNotice, args)

proc info*(args: varargs[string, `$`]) =
    log(lvlInfo, args)

proc debug*(args: varargs[string, `$`]) =
    log(lvlDebug, args)

proc getLogLevel*(): string =
  return LevelNames[LOGLEVEL].toLowerAscii

proc setLogFilter*(lvl: Level) =
    LOGLEVEL = lvl

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
  LOGLEVEL = lvl
  return val