Skip to content

Commit

Permalink
Fix: dedup works with multistream (refs: #1506) (#1508)
Browse files Browse the repository at this point in the history
  • Loading branch information
bl00dhound committed Aug 4, 2022
1 parent b288da5 commit d15be16
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 4 deletions.
29 changes: 25 additions & 4 deletions lib/multistream.js
Expand Up @@ -47,10 +47,18 @@ function multistream (streamsArray, opts) {
let dest
const level = this.lastLevel
const { streams } = this
// for handling situation when several streams has the same level
let recordedLevel = 0
let stream
for (let i = 0; i < streams.length; i++) {

// if dedupe set to true we send logs to the stream with the highest level
// therefore, we have to change sorting order
for (let i = initLoopVar(streams.length, opts.dedupe); checkLoopVar(i, streams.length, opts.dedupe); i = adjustLoopVar(i, opts.dedupe)) {
dest = streams[i]
if (dest.level <= level) {
if (recordedLevel !== 0 && recordedLevel !== dest.level) {
break
}
stream = dest.stream
if (stream[metadata]) {
const { lastTime, lastMsg, lastObj, lastLogger } = this
Expand All @@ -60,10 +68,11 @@ function multistream (streamsArray, opts) {
stream.lastObj = lastObj
stream.lastLogger = lastLogger
}
if (!opts.dedupe || dest.level === level) {
stream.write(data)
stream.write(data)
if (opts.dedupe) {
recordedLevel = dest.level
}
} else {
} else if (!opts.dedupe) {
break
}
}
Expand Down Expand Up @@ -153,4 +162,16 @@ function compareByLevel (a, b) {
return a.level - b.level
}

function initLoopVar (length, dedupe) {
return dedupe ? length - 1 : 0
}

function adjustLoopVar (i, dedupe) {
return dedupe ? i - 1 : i + 1
}

function checkLoopVar (i, length, dedupe) {
return dedupe ? i >= 0 : i < length
}

module.exports = multistream
35 changes: 35 additions & 0 deletions test/multistream.test.js
Expand Up @@ -434,6 +434,41 @@ test('dedupe', function (t) {
t.end()
})

test('dedupe when logs have different levels', function (t) {
let messageCount = 0
const stream1 = writeStream(function (data, enc, cb) {
messageCount += 1
cb()
})

const stream2 = writeStream(function (data, enc, cb) {
messageCount += 2
cb()
})

const streams = [
{
stream: stream1,
level: 'info'
},
{
stream: stream2,
level: 'error'
}
]

const log = pino({
level: 'trace'
}, multistream(streams, { dedupe: true }))

log.info('info stream')
log.warn('warn stream')
log.error('error streams')
log.fatal('fatal streams')
t.equal(messageCount, 6)
t.end()
})

test('dedupe when some streams has the same level', function (t) {
let messageCount = 0
const stream1 = writeStream(function (data, enc, cb) {
Expand Down

0 comments on commit d15be16

Please sign in to comment.