Skip to content

Instantly share code, notes, and snippets.

@jehugaleahsa
Last active January 26, 2017 16:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jehugaleahsa/feea687b55207e3faa3b64170744f3c2 to your computer and use it in GitHub Desktop.
Save jehugaleahsa/feea687b55207e3faa3b64170744f3c2 to your computer and use it in GitHub Desktop.
Custom NLog Json formatter driven by Exception.Data
[LayoutRenderer("event-id-json-data")]
public class EventIdLayoutRenderer : LayoutRenderer
{
private const string _eventIdKey = "EventId";
private static JsonSerializerSettings _jsonSettings = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
};
protected override void Append(StringBuilder builder, LogEventInfo logEvent)
{
if (logEvent.Properties == null)
{
return;
}
if (!logEvent.Properties.ContainsKey(_eventIdKey))
{
return;
}
var eventId = (EventId)logEvent.Properties[_eventIdKey];
var result = new
{
Id = eventId.Id,
Name = eventId.Name
};
var resultString = JsonConvert.SerializeObject(result, _jsonSettings);
builder.Append(resultString);
}
}
{
"time": "2016-06-01T18:54:04.834Z",
"level": "ERROR",
"message": "Home page view exception!",
"event": {
"Id": 101,
"Name": "Page View"
},
"exceptionMessage": "This is a not implemented exception",
"exceptionStackTrace": "System.NotImplementedException: This is a not implemented exception ---> System.ArgumentNullException: Value cannot be null.\r\nParameter name: This is an arg null exception\r\n --- End of inner exception stack trace ---",
"exceptionData": {
"userId": 5
}
}
[LayoutRenderer("exception-json-data")]
public class ExceptionDataLayoutRenderer : LayoutRenderer
{
protected override void Append(StringBuilder builder, LogEventInfo logEvent)
{
var exception = logEvent.Exception;
if (exception == null)
{
return;
}
var data = getExceptionData(exception);
var result = JsonConvert.SerializeObject(data);
builder.Append(result);
}
private IDictionary<string, object> getExceptionData(Exception ex)
{
if (ex == null)
{
return new Dictionary<string, object>();
}
var innerData = getExceptionData(ex.InnerException);
var data = ex.Data.Cast<DictionaryEntry>()
.Where(x => x.Key is string)
.ToDictionary(x => x.Key as string, x => x.Value);
return data.Extend(innerData);
}
}
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
autoReload="true"
throwExceptions="false"
internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log" >
<variable name="myvar" value="myvalue"/>
<time xsi:type="FastUTC" />
<extensions>
<add assembly="CoreDemo" />
</extensions>
<targets async="true">
<!-- Write events to a file with the date in the filename. -->
<target xsi:type="File"
name="f"
fileName="${basedir}/logs/${shortdate}.log"
keepFileOpen="true">
<layout xsi:type="JsonLayout">
<attribute name="time" layout="${date:format=yyyy-MM-ddTHH\:mm\:ss.fffK}" />
<attribute name="level" layout="${level:upperCase=true}"/>
<attribute name="message" layout="${message}" />
<attribute name='event' layout='${event-id-json-data}' encode='false' />
<attribute name='exceptionMessage' layout='${exception}' />
<attribute name='exceptionStackTrace' layout='${exception:format=ToString}' />
<attribute name='exceptionData' layout='${exception-json-data}' encode='false' />
</layout>
</target>
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="f" />
</rules>
</nlog>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment