Level Up Coding

Coding tutorials and news. The developer homepage gitconnected.com && skilled.dev && levelup.dev

Follow publication

Member-only story

Beware of Using JSON.stringify() for Logging

John Mills
Level Up Coding
Published in
3 min readAug 23, 2020

--

String on a fence
Photo by Rosie Kerr on Unsplash

Recently I was working on a legacy system built on AWS Lambda and Node.js. It uses the console object along with JSON.stringify() to log messages and data to AWS CloudWatch.

The log messages often contain helpful clues that assist with troubleshooting issues, particularly when they only show up in the production environment.

By running the example below and expanding the output, you can see how including JSON data in log messages might be really helpful. Log tools such as Sumo Logic can work with the JSON data embedded in log messages.

However, when used with JavaScript errors, specifically, objects inheriting from the Error class. The technique does more harm than good. The output from using JSON.stringify() with an error is an empty object !

Back to the legacy system I was working on. I was investigating some issues reported by our users. While browsing the logs, I noticed that many errors had little useful information and were proving difficult to understand. These error messages were logged using JSON.stringify().

So why does a technique that works great for logging plain objects not work at all for logging errors? It is because JSON.stringify() only includes enumerable properties and the Error class doesn’t have any, hence the output of {}.

Running the example below demonstrates the difference between the properties on regular objects and errors.

--

--

Written by John Mills

John is a software developer living in Wellington, New Zealand. He writes about code, tech, travel & “ancient” New Zealand.

No responses yet

Write a response