Usually I log my objects data through Newtonsoft JsonConvert.SerializeObject()
which serializes to a string the object's contents.
But instead of having KeyValue pairs separated by : I want them to be separated by = to be logged by Splunk.
So instead of having like
{ "Name": "John", Age : 18 }
I want
{ "Name" = "John", Age = 18 }
Of course I am also looking for something that should work for objects inside objects.. From the API seems a bit rigid to format the separator differently than : because it's not a JSON format at the end of the day.
There is any easy way to do this instead of reinvent the wheel?
This should be doable with Json.NET, but not with with a custom
JsonConverter
. Newtonsoft maintains a distinction between its serializer, which recursively walks a c# object graph emitting abstract lists and objects containing key/value pairs, and its writer, which formats and outputs the results of serialization according to some particular standard. You can take advantage of this distinction to create your own custom subclass ofJsonWriter
that formats your keys and values in Splunk's desired manner.That being said, there's an inconsistency in your question: you quote the
"Name"
property name, but not theAge
property name. If you want to have special rules where certain property names are quoted but others are not, I can't see a straightforward way to do that with Json.NET. However, in Logging best practices Splunk writes:Thus it would appear that selective quoting of property names is not needed.
Assuming that is the case, when creating a custom
JsonWriter
, you can use the following writers as models, both created by James Newton-King of Newtonsoft:BsonWriter
JsonTextWriter
Based on these two classes I whipped up a partial implementation of
SplunkLogTextWriter
that generates output in your required format:Then if you use it as follows:
The following result is generated:
Note that some portions of the writer are not implemented yet. Look for
ToDo
comments andNotImplementedException
throws. You will also need to tweak the writer given the formal definition of the logging format, which your question does not provide.Sample fiddle.