Skip to content

Instantly share code, notes, and snippets.

@danesparza
Created January 12, 2016 19:10
Show Gist options
  • Save danesparza/afa9255032fd65ef0808 to your computer and use it in GitHub Desktop.
Save danesparza/afa9255032fd65ef0808 to your computer and use it in GitHub Desktop.
NLog extension to log objects associated with a requestId
public static class NLogExtensions
{
/// <summary>
/// Logs the item with an associated requestid
/// </summary>
/// <param name="logger">The logger to use</param>
/// <param name="level">The log level to use</param>
/// <param name="objectToLog">The object to serialize</param>
/// <param name="message">The message to associate with the serialized object</param>
/// <param name="requestId">The requestid to associate with this item</param>
/// <param name="ex">The exception to associate with the serialized object</param>
/// <returns></returns>
public static void SerializeToLog(this Logger logger, object objectToLog, string message, NLogLevel level = NLogLevel.Debug, string requestId = "", Exception ex = null)
{
// If we're not tracking a requestId in the global diagnostics context, see if we were passed one:
if(!GlobalDiagnosticsContext.Contains("RequestId"))
{
// If we weren't passed one, create one:
if(string.IsNullOrEmpty(requestId))
{
requestId = Guid.NewGuid().ToString("N");
}
// Track the requestId
// (See http://stackoverflow.com/a/12427504/19020 for more information)
GlobalDiagnosticsContext.Set("RequestId", requestId);
}
// Format the item:
var logItem = new
{
LogMessage = message,
LogObject = objectToLog
};
// Dump to string safely (and without type info):
string formattedLogItem = string.Empty;
using(JsConfig.With(excludeTypeInfo: true))
{
try
{ formattedLogItem = logItem.Dump(); }
catch(Exception) { }
}
// Log the item with the exception if we have one... otherwise just log it
if(ex != null)
{
logger.Log(LogLevel.FromOrdinal((int)level), formattedLogItem, ex);
}
else
{
logger.Log(LogLevel.FromOrdinal((int)level), formattedLogItem);
}
}
}
/// <summary>
/// Corresponds to NLog log levels.
/// </summary>
public enum NLogLevel
{
Trace = 0,
Debug = 1,
Info = 2,
Warn = 3,
Error = 4,
Fatal = 5
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment