Use a table for thread-global cache, hierarchical logging namespaces.

This commit is contained in:
Jonathan Bernard 2022-06-04 21:48:25 -05:00
parent 79c3701f26
commit 8245cfbdf7
2 changed files with 19 additions and 7 deletions

View File

@ -1,6 +1,6 @@
# Package # Package
version = "0.1.0" version = "0.2.0"
author = "Jonathan Bernard" author = "Jonathan Bernard"
description = "Wrapper around std/logging to provide namespaced logging." description = "Wrapper around std/logging to provide namespaced logging."
license = "MIT" license = "MIT"

View File

@ -1,4 +1,4 @@
import logging, sequtils, strutils import logging, sequtils, strutils, tables
export logging.Level export logging.Level
@ -8,7 +8,12 @@ type
level*: Level level*: Level
msgPrefix*: string msgPrefix*: string
var knownNamespaces {.threadvar.}: seq[LoggingNamespace] var knownNamespacesInst {.threadvar.}: TableRef[string, LoggingNamespace]
template knownNamespaces(): TableRef[string, LoggingNamespace] =
if knownNamespacesInst == nil:
knownNamespacesInst = newTable[string, LoggingNamespace]()
knownNamespacesInst
proc initLoggingNamespace*(name: string, level = lvlInfo, msgPrefix: string): LoggingNamespace = proc initLoggingNamespace*(name: string, level = lvlInfo, msgPrefix: string): LoggingNamespace =
result = LoggingNamespace( result = LoggingNamespace(
@ -16,14 +21,21 @@ proc initLoggingNamespace*(name: string, level = lvlInfo, msgPrefix: string): Lo
level: level, level: level,
msgPrefix: msgPrefix) msgPrefix: msgPrefix)
knownNamespaces.add(result) knownNamespaces[name] = result
proc initLoggingNamespace*(name: string, level = lvlInfo): LoggingNamespace = proc initLoggingNamespace*(name: string, level = lvlInfo): LoggingNamespace =
return initLoggingNamespace(name, level, name & ": ") return initLoggingNamespace(name, level, name & ": ")
proc setLevelForNamespace*(namespace: string, lvl: Level) = proc getLoggerForNamespace*(namespace: string, level = lvlInfo): LoggingNamespace =
let found = knownNamespaces.filterIt(it.name == namespace) if knownNamespaces.hasKey(namespace): return knownNamespaces[namespace]
for ns in found: ns.level = lvl else: return initLoggingNamespace(namespace, level)
proc setLevelForNamespace*(namespace: string, lvl: Level, recursive = false) =
if recursive:
for k, v in knownNamespaces.pairs:
if k.startsWith(namespace):
v.level = lvl
elif knownNamespaces.hasKey(namespace): knownNamespaces[namespace].level = lvl
proc name*(ns: LoggingNamespace): string = ns.name proc name*(ns: LoggingNamespace): string = ns.name
proc log*(ns: LoggingNamespace, level: Level, args: varargs[string, `$`]) = proc log*(ns: LoggingNamespace, level: Level, args: varargs[string, `$`]) =