pino: Including a BigInt in the merging object throws an exception

Pino seems unable to handle BigInts. Tested in 6.7.0:

> const logger = require('pino')();
> logger.info({ t: 10n }, "Hello");
Uncaught TypeError: Do not know how to serialize a BigInt
    at JSON.stringify (<anonymous>)
    at stringify (/Users/dave/workspace/pixelbin/node_modules/fast-safe-stringify/index.js:14:16)
    at stringify (/Users/dave/workspace/pixelbin/node_modules/pino/lib/tools.js:403:12)
    at Pino.asJson (/Users/dave/workspace/pixelbin/node_modules/pino/lib/tools.js:139:45)
    at Pino.write (/Users/dave/workspace/pixelbin/node_modules/pino/lib/proto.js:165:28)
    at Pino.LOG [as info] (/Users/dave/workspace/pixelbin/node_modules/pino/lib/tools.js:55:21)

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Reactions: 2
  • Comments: 22 (10 by maintainers)

Most upvoted comments

I’ve had the same problem.

As pointed by @kf6kjg, for better performances, the ugly way could be:

BigInt.prototype.toJSON = function() { return this.toString() };

But the global prototype poisoning could be harmful. So I found an alternative way based on that:

const pino = require('pino');
const pinoSymbols = require('pino/lib/symbols');
const log = pino();
log[pinoSymbols.stringifySym] = function(_obj) {
  const original = BigInt.prototype.toJSON;
  BigInt.prototype.toJSON = function() { return this.toString() }; // Change with whatever serialization you want
  const res = JSON.stringify(_obj);
  BigInt.prototype.toJSON = original;
  return res;
}

For 10M log.info({test:{}}) calls on my system:

  • Without the patch: 40.090 ms
  • With the patch: 42.227 ms

That’s a 5% overhead.