Skip to content

Commit

Permalink
fix: throttle expiration (#81)
Browse files Browse the repository at this point in the history
fixes #68
  • Loading branch information
Akryum authored and pi0 committed Dec 27, 2019
1 parent 8bea95e commit 940474d
Show file tree
Hide file tree
Showing 3 changed files with 74 additions and 243 deletions.
52 changes: 35 additions & 17 deletions src/consola.js
Expand Up @@ -35,6 +35,7 @@ class Consola {
this._lastLog = null
this._lastLogTime = null
this._lastLogCount = 0
this._throttleTimeout = null
}

get level () {
Expand Down Expand Up @@ -254,7 +255,38 @@ class Consola {
logObj.type = typeof logObj.type === 'string' ? logObj.type.toLowerCase() : ''
logObj.tag = typeof logObj.tag === 'string' ? logObj.tag.toLowerCase() : ''

// Resolve log
/**
* @param newLog false if the throttle expired and
* 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
}
this._lastLog = logObj

// Log
if (newLog) {
if (this._async) {
return this._logAsync(logObj)
} else {
this._log(logObj)
}
}
}

// Throttle
clearTimeout(this._throttleTimeout)
const diffTime = this._lastLogTime ? logObj.date - this._lastLogTime : 0
this._lastLogTime = logObj.date
if (diffTime < this._throttle) {
Expand All @@ -264,30 +296,16 @@ class Consola {
this._lastLogSerialized = serializedLog
if (isSameLog) {
this._lastLogCount++
// Auto-resolve when throttle is timed out
this._throttleTimeout = setTimeout(resolveLog, this._throttle)
return // SPAM!
}
} catch (_) {
// Circular References
}
}
if (this._lastLogCount) {
this._log({
...this._lastLog,
args: [
...this._lastLog.args,
`(repeated ${this._lastLogCount} times)`
]
})
this._lastLogCount = 0
}
this._lastLog = logObj

// Log
if (this._async) {
return this._logAsync(logObj)
} else {
this._log(logObj)
}
resolveLog(true)
}

_log (logObj) {
Expand Down
28 changes: 28 additions & 0 deletions test/consola.test.js
Expand Up @@ -17,4 +17,32 @@ describe('consola', () => {
consola.level = -99
expect(consola.level).toBe(0)
})

test('can see spams without ending log', async () => {
const logs = []
class TestReporter {
log (logObj) {
logs.push(logObj)
}
}

const consola = new Consola({
throttle: 100,
reporters: [
new TestReporter()
]
})
for (let i = 0; i < 10; i++) {
consola.log('SPAM')
}
await wait(200)
expect(logs.length).toBe(2)
expect(logs[1].args).toEqual(['SPAM', '(repeated 9 times)'])
})
})

function wait (delay) {
return new Promise((resolve) => {
setTimeout(resolve, delay)
})
}

0 comments on commit 940474d

Please sign in to comment.