From 5314eeebb4b564408a4ab14cb457bdbd426f6124 Mon Sep 17 00:00:00 2001 From: pooya parsa Date: Fri, 26 Jun 2020 17:02:14 +0200 Subject: [PATCH] feat: improve spam throttle --- examples/spam.js | 20 ++++++++++++++------ src/consola.js | 30 +++++++++++++++--------------- 2 files changed, 29 insertions(+), 21 deletions(-) diff --git a/examples/spam.js b/examples/spam.js index cded3fe..2cf0352 100755 --- a/examples/spam.js +++ b/examples/spam.js @@ -2,12 +2,20 @@ import { consola } from './utils' -function spam (msg, level = 'warn', count = 10) { - for (let i = 0; i < 10; i++) { - consola[level](msg) +function waitFor (ms) { + return new Promise(resolve => setTimeout(resolve, ms)) +} + +async function spam ({ count, delay }) { + for (let i = 0; i < count; i++) { + await waitFor(delay) + consola.log(`Spam (Count: ${count} Delay: ${delay} ms)`) } } -spam('FOOOOOOO FOOOOOOOOO') -consola.log('bar') -spam('FOOOOOOO FOOOOOOOOO') +(async () => { + await spam({ count: 2, delay: 10 }) + await spam({ count: 20, delay: 10 }) + await spam({ count: 20, delay: 0 }) + await spam({ count: 80, delay: 10 }) +})() diff --git a/src/consola.js b/src/consola.js index b0beb1e..d88784a 100644 --- a/src/consola.js +++ b/src/consola.js @@ -14,7 +14,8 @@ class Consola { this._stdout = options.stdout this._stderr = options.stderr this._mockFn = options.mockFn - this._throttle = options.throttle || 2000 + this._throttle = options.throttle || 1000 + this._throttleMin = options.throttleMin || 5 // Create logger functions for current instance for (const type in this._types) { @@ -241,22 +242,19 @@ class Consola { * we don't want to log a duplicate */ const resolveLog = (newLog = false) => { - if (this._lastLogCount) { - this._log({ - ...this._lastLog, - args: [ - ...this._lastLog.args, - // Minus one since we logged the message once already - // before queuing the duplicates - `(repeated ${this._lastLogCount - (newLog ? 1 : 0)} times)` - ] - }) - this._lastLogCount = 0 + const repeated = this._lastLogCount - this._throttleMin + if (this._lastLog && repeated > 0) { + const args = [...this._lastLog.args] + if (repeated > 1) { + args.push(`(repeated ${repeated} times)`) + } + this._log({ ...this._lastLog, args }) + this._lastLogCount = 1 } - this._lastLog = logObj // Log if (newLog) { + this._lastLog = logObj if (this._async) { return this._logAsync(logObj) } else { @@ -276,9 +274,11 @@ class Consola { this._lastLogSerialized = serializedLog if (isSameLog) { this._lastLogCount++ + if (this._lastLogCount > this._throttleMin) { // Auto-resolve when throttle is timed out - this._throttleTimeout = setTimeout(resolveLog, this._throttle) - return // SPAM! + this._throttleTimeout = setTimeout(resolveLog, this._throttle) + return // SPAM! + } } } catch (_) { // Circular References