I'm looking to write a log file in JSON.
After looking at a few libraries for formatting inspiration and best practices (Winston for Node.JS, Apache's JSON logging option, etc.), I've noticed that almost all of them write multiple root elements vs. using an Array or Root Element.
Example:
{"time":"2012-09-20T20:27:59Z","level":"info","message":"Hello World"} {"time":"2012-09-20T21:37:59Z","level":"info","message":"Hello Again"}
vs.
[{"time":"2012-09-20T20:27:59Z","level":"info","message":"Hello World"},{"time":"2012-09-20T21:37:59Z","level":"info","message":"Hello Again"}]
Why is this done when technically it's not valid JSON to have multiple root elements?
When logging you keep adding new log entries. How would you know when to close the array? When is your logging "complete"? You could start the log with an empty array, [], but then when adding an entry you'd have to keep seeking back in the file to find the right place, and check whether a comma was needed or not.
Or you an just write each entry as a separate root object, and each time you write something out it's independent and appends to the end of the file. That's much simpler.
The log is not a single JSON object, i.e the entire log doesn't form a valid JSON string. It's a sequence of independent JSON objects. The individual entries are the units you should be considering, not the entire log as a whole.
Because log is increasing every seconds.
Without Root elemet,the new log could just append with old items. If have a root element,or in an array,you have to query the new log items,and append it.
so,you have the right choice.