From 05703fc86f81b5db050d70746af19183394cf326 Mon Sep 17 00:00:00 2001 From: mratsim Date: Fri, 15 Jun 2018 14:20:42 +0200 Subject: [PATCH] logging: non-debug costless, avoid allocating constant string messages --- nimbus/logging.nim | 29 ++++++++++++++++++----------- tests/test_gas_meter.nim | 2 +- 2 files changed, 19 insertions(+), 12 deletions(-) diff --git a/nimbus/logging.nim b/nimbus/logging.nim index 8caf9c04e..46d205be4 100644 --- a/nimbus/logging.nim +++ b/nimbus/logging.nim @@ -7,29 +7,36 @@ import strformat, terminal +# TODO replace by nim-chronicles + type Logger* = object name*: string -var DEBUG* = defined(nimbusdebug) +const DEBUG* = defined(nimbusdebug) -proc log*(l: Logger, msg: string, color: ForegroundColor = fgBlack) = - if DEBUG: +# Note: to make logging costless: +# - DEBUG should be a const and dispatch should use `when` for compile-time specialization +# - Passing a string to a proc, even a const string and inline proc, might trigger a heap allocation +# use a template instead. + +template log*(l: Logger, msg: string, color: ForegroundColor = fgBlack) = + when DEBUG: styledWriteLine(stdout, color, &"#{l.name}: {msg}", resetStyle) -proc debug*(l: Logger, msg: string) = - if DEBUG: +template debug*(l: Logger, msg: string) = + when DEBUG: l.log(msg) -proc trace*(l: Logger, msg: string) = - if DEBUG: +template trace*(l: Logger, msg: string) = + when DEBUG: l.log(msg, fgBlue) proc getLogger*(name: string): Logger = result = Logger(name: name) -proc disableLogging* = - DEBUG = false +# proc disableLogging* = +# DEBUG = false -proc enableLogging* = - DEBUG = true +# proc enableLogging* = +# DEBUG = true diff --git a/tests/test_gas_meter.nim b/tests/test_gas_meter.nim index 9ad8e7aa5..542b2bb47 100644 --- a/tests/test_gas_meter.nim +++ b/tests/test_gas_meter.nim @@ -12,7 +12,7 @@ import unittest, macros, strformat, # TODO: quicktest # PS: parametrize can be easily immitated, but still quicktests would be even more useful -disableLogging() +# disableLogging() proc gasMeters: seq[GasMeter] = @[newGasMeter(10), newGasMeter(100), newGasMeter(999)]