Skip to content

Commit

Permalink
Merge pull request #50 from apehead/safe-stringify
Browse files Browse the repository at this point in the history
Add safe stringify
  • Loading branch information
mcollina committed Dec 11, 2018
2 parents d35416a + 1d036b3 commit 6982154
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 2 deletions.
5 changes: 3 additions & 2 deletions index.js
Expand Up @@ -5,6 +5,7 @@ const dateformat = require('dateformat')
// remove jsonParser once Node 6 is not supported anymore
const jsonParser = require('fast-json-parse')
const jmespath = require('jmespath')
const stringifySafe = require('fast-safe-stringify')

const CONSTANTS = require('./lib/constants')

Expand Down Expand Up @@ -224,7 +225,7 @@ module.exports = function prettyFactory (options) {

for (var i = 0; i < keys.length; i += 1) {
if (errorLikeObjectKeys.indexOf(keys[i]) !== -1 && value[keys[i]] !== undefined) {
const lines = JSON.stringify(value[keys[i]], null, 2)
const lines = stringifySafe(value[keys[i]], null, 2)
if (lines === undefined) continue
const arrayOfLines = (
IDENT + keys[i] + ': ' +
Expand Down Expand Up @@ -254,7 +255,7 @@ module.exports = function prettyFactory (options) {
}
} else if (filteredKeys.indexOf(keys[i]) < 0) {
if (value[keys[i]] !== undefined) {
const lines = JSON.stringify(value[keys[i]], null, 2)
const lines = stringifySafe(value[keys[i]], null, 2)
if (lines !== undefined) {
result += IDENT + keys[i] + ': ' + joinLinesWithIndentation(lines) + EOL
}
Expand Down
1 change: 1 addition & 0 deletions package.json
Expand Up @@ -34,6 +34,7 @@
"chalk": "^2.3.2",
"dateformat": "^3.0.3",
"fast-json-parse": "^1.0.3",
"fast-safe-stringify": "^2.0.6",
"jmespath": "^0.15.0",
"pump": "^3.0.0",
"readable-stream": "^3.0.6",
Expand Down
29 changes: 29 additions & 0 deletions test/basic.test.js
Expand Up @@ -485,6 +485,35 @@ test('basic prettifier tests', (t) => {
log.info({ msg: { b: { c: 'd' } } })
})

t.test('prettifies msg object with circular references', (t) => {
t.plan(7)
const expectedLines = [
' msg: {',
' "b": {',
' "c": "d"',
' },',
' "a": "[Circular]"',
' }'
]
const pretty = prettyFactory()
const log = pino({}, new Writable({
write (chunk, enc, cb) {
const formatted = pretty(chunk.toString())
const lines = formatted.split('\n')
t.is(lines.length, expectedLines.length + 2)
lines.shift(); lines.pop()
for (var i = 0; i < lines.length; i += 1) {
t.is(lines[i], expectedLines[i])
}
cb()
}
}))

const msg = { b: { c: 'd' } }
msg.a = msg
log.info({ msg })
})

t.test('prettifies object with some undefined values', (t) => {
t.plan(1)
const dest = new Writable({
Expand Down

0 comments on commit 6982154

Please sign in to comment.