How can I serialize exceptions to SLAB, nicely?

Topics: Semantic Logging Application Block
May 9, 2013 at 8:47 PM
Edited May 9, 2013 at 8:48 PM
I've just started playing with SLAB. I'm impressed how easy it was to get stuff into a DB compared to the old logging block. Now, I'm looking at logging exceptions. I used a wrapper to log a complex object and what was stored in the Payload of the table looks like JSON. When I serialized an Exception and added it to the payload, I got escaped quotes, e.g.
    "ExceptionType": "System.ArgumentNullException",
    "ExceptionMessage": "Value cannot be null.\r\nParameter name: arg",
    "SerializedException": "{\"ClassName\":\"System.ArgumentNullException\", ... etc.
Is there any way to get it in there as a proper nested JSON object?
May 9, 2013 at 11:05 PM

Not sure if I get your point since the escaping is done as part of the JSON serialization process like quotes or new line chars. In case you want more control of the properties that conform the payload and assuming you want to use the DB sinks (azure/SQL) you can define as your event arguments the specific properties of the exception that you want to persist and do some kind of "sanitization" to extract/replace any character you don't want to be encoded.
Another option is to use some of the formatters (or custom) in case you use a file sink so you may have a fine grain control of the serialization process.

May 10, 2013 at 2:19 PM
Edited May 10, 2013 at 2:20 PM
Prompted by your first line, I investigated Newtonsoft.Json a bit more. I now understand your confusion at my confusion!

I don't normally work with JSON but thought that nested types were done without escaping. Of course, that's only when they're serialized in one step. Doh! Put it down to a long day. :-(

I've changed the code that produced the above just to log SerializedException and to use JsonSerializerSettings with TypeNameHandling.All to record the Types being serialized, so that I can reconstitute them - this is supposed to be semantic logging, after all. :-)

The following works (I've used EntityFramework to retrieve a trace record from the Logging.dbo.Traces table):
    settings = new JsonSerializerSettings();
    settings.TypeNameHandling = TypeNameHandling.All;

    var trace = context.Traces.Where(t => == 26).First();
    var payload = trace.Payload;
    var deserializedPayload = (JObject)JsonConvert.DeserializeObject(payload);
    var serializedException = 
    var exception = JsonConvert.DeserializeObject(serializedException, settings);
but is it there another way to reconstitute it that would be considered better?

Or a different approach altogether?