Skip to content

Commit

Permalink
fix: support logging errors that do not contain a stack (#457)
Browse files Browse the repository at this point in the history
Custom errors may not have their stack property set.
Pino used to serialize undefined stack which created invalid JSON output
  • Loading branch information
disintegrator authored and mcollina committed Jul 20, 2018
1 parent ed4428e commit 3a14789
Show file tree
Hide file tree
Showing 4 changed files with 38 additions and 2 deletions.
3 changes: 2 additions & 1 deletion pino.js
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,8 @@ function asJson (obj, msg, num, time) {
if (hasObj) {
var notHasOwnProperty = obj.hasOwnProperty === undefined
if (objError) {
data += ',"type":"Error","stack":' + this.stringify(obj.stack)
data += ',"type":"Error"'
data += obj.stack ? ',"stack":' + this.stringify(obj.stack) : ''
}
// if global serializer is set, call it first
if (this.serializers[Symbol.for('pino.*')]) {
Expand Down
4 changes: 3 additions & 1 deletion pretty.js
Original file line number Diff line number Diff line change
Expand Up @@ -217,7 +217,9 @@ function pretty (opts) {
line += eol

if (value.type === 'Error') {
line += ' ' + withSpaces(value.stack, eol) + eol
line += value.stack
? ' ' + withSpaces(value.stack, eol) + eol
: ''

var propsForPrint
if (errorProps && errorProps.length > 0) {
Expand Down
15 changes: 15 additions & 0 deletions test/error.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -128,3 +128,18 @@ test('an error with statusCode property is not confused for a http response', fu
instance.level = name
instance[name](err)
})

test('stack is omitted if it is not set on err', t => {
t.plan(2)
var err = new Error('myerror')
delete err.stack
var instance = pino(sink(function (chunk, enc, cb) {
t.ok(new Date(chunk.time) <= new Date(), 'time is greater than Date.now()')
delete chunk.time
t.equal(chunk.hasOwnProperty('stack'), false)
cb()
}))

instance.level = name
instance[name](err)
})
18 changes: 18 additions & 0 deletions test/pretty.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,24 @@ test('pino transform prettifies Error', function (t) {
instance.info(err)
})

test('pino transform prettifies Error without stack', function (t) {
var prettier = pretty()
var err = new Error('hello world')
delete err.stack
var expected = [err.message]

t.plan(expected.length)

prettier.pipe(split(function (line) {
t.ok(line.indexOf(expected.shift()) >= 0, 'line matches')
return line
}))

var instance = pino(prettier)

instance.info(err)
})

function getIndentLevel (str) {
return (/^\s*/.exec(str) || [''])[0].length
}
Expand Down

0 comments on commit 3a14789

Please sign in to comment.