serialize objects or collections to log

Yavanosta picture Yavanosta · Apr 11, 2014 · Viewed 13.2k times · Source

I want save some addtitional info with my error message. For example it should be user query, or something else. How should I do it?

Is there any build it methods for logging collections, structurest or objects? Or I should serialize it myself?

Answer

Sergey Berezovskiy picture Sergey Berezovskiy · Apr 11, 2014

No, there is nothing built-in for serializing objects. When you use formatted methods like Debug<T>(string message, T argument) internally (you can see class NLog.LogEventInfo) simple String.Format is used for creating formatted message (i.e. just ToString() is called on every parameter).

I use Json.NET for serializing objects and collections to JSON. It's easy to create extension method like

public static string ToJson(this object value)
{
    var settings = new JsonSerializerSettings { 
        ReferenceLoopHandling = ReferenceLoopHandling.Ignore 
    };

    return JsonConvert.SerializeObject(value, Formatting.Indented, settings);
}

And then use it during logging:

Logger.Debug("Saving person {0}", person.ToJson());