Documentation Menu
Logging cyclic references
- A working demo is in project JSNLogDemo_Log4Net_Decycle
Some objects have cyclic references. That is, they refer to themselves. For example:
var a = { x: 1 }; a.self = a;
The problem is that the JSON.stringify method used to serialize objects into strings cannot handle this. Instead, it throws an exception, such as:
Uncaught TypeError: Converting circular structure to JSON
The solution is to use the JL.serialize option to set a custom method that does handle cyclic references:
- Find yourself a library that deals with cyclic references. Personally I like cycle.js.
-
Write a method that takes an object, serializes it, and returns the resulting string. Such as this:
<script src="cycle.js"></script> var decyclingSerializer = function(obj) { // JSON.decycle is defined in cycle.js var decycledObject = JSON.decycle(obj); return JSON.stringify(decycledObject); }
-
Tell JSNLog to use your new method:
JL.setOptions({ "serialize": decyclingSerializer });