diff --git a/README.md b/README.md index 13e71c94..2eb4a5d0 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,7 @@ - Browser support - Pause/Resume support - Mocking support +- Spam preventation by throttling logs ## Installation diff --git a/examples/spam.js b/examples/spam.js new file mode 100755 index 00000000..cded3fe2 --- /dev/null +++ b/examples/spam.js @@ -0,0 +1,13 @@ +#!/usr/bin/env node -r esm + +import { consola } from './utils' + +function spam (msg, level = 'warn', count = 10) { + for (let i = 0; i < 10; i++) { + consola[level](msg) + } +} + +spam('FOOOOOOO FOOOOOOOOO') +consola.log('bar') +spam('FOOOOOOO FOOOOOOOOO') diff --git a/src/consola.js b/src/consola.js index 2b672764..37d0cbc9 100644 --- a/src/consola.js +++ b/src/consola.js @@ -14,6 +14,7 @@ class Consola { this._stdout = options.stdout this._stderr = options.stdout this._mockFn = options.mockFn + this._throttle = options.throttle || 2000 // Create logger functions for current instance for (const type in this._types) { @@ -28,6 +29,10 @@ class Consola { if (this._mockFn) { this.mockTypes() } + + // Keep serialized version of last message + this._lastMessage = null + this._lastMessageTime = null } get level () { @@ -251,6 +256,22 @@ class Consola { logObj.tag = logObj.tag.toLowerCase() } + // Throttle + const diffTime = this._lastMessageTime ? logObj.date - this._lastMessageTime : 0 + this._lastMessageTime = logObj.date + if (diffTime < this._throttle) { + try { + const serializedMessage = JSON.stringify([logObj.type, logObj.tag, logObj.args]) + const isSameMessage = this._lastMessage === serializedMessage + this._lastMessage = serializedMessage + if (isSameMessage) { + return // SPAM! + } + } catch (_) { + // Circular References + } + } + // Log if (this._async) { return this._logAsync(logObj)