Skip to content

Commit

Permalink
feat: improve spam throttle
Browse files Browse the repository at this point in the history
  • Loading branch information
pooya parsa committed Jun 26, 2020
1 parent 182725d commit 5314eee
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 21 deletions.
20 changes: 14 additions & 6 deletions examples/spam.js
Expand Up @@ -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 })
})()
30 changes: 15 additions & 15 deletions src/consola.js
Expand Up @@ -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) {
Expand Down Expand Up @@ -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 {
Expand All @@ -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
Expand Down

0 comments on commit 5314eee

Please sign in to comment.