log4javascript is a nice logging framework for JavaScript. With it you can log to the browser console (if supported by the browser), but also to an own window and even to the server via AJAX calls. For the latter, you need also something on the server which can handle the AJAX requests. Here I wanted to use ASP.NET Web Api. Since I didn’t find any documentation on this specific topic, I want to share my experiences here.
In general, the whole stuff is quite easy. On the client side you have to define the AjaxAppender:
1 2 3 | var ajaxAppender = new log4javascript.AjaxAppender(serverUrl); ajaxAppender.setLayout( new log4javascript.JsonLayout()); ajaxAppender.addHeader( "Content-Type" , "application/json; charset=utf-8" ); |
After specifying the correct content type, Web Api uses the JsonMediaTypeFormatter. And everything is fine.
On the server side, I first had to define the structure of the log data:
1 2 3 4 5 6 7 8 | public struct LogEntry { public string Logger; public long Timestamp; public string Level; public string Url; public string Message; } |
1 2 3 4 5 6 7 8 9 10 11 12 | public void Write(LogEntry[] data) { if (data != null ) { foreach (LogEntry entry in data) { DateTime timestampUtc = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(entry.Timestamp); DateTime timestampLocal = timestampUtc.ToLocalTime(); ... } } } |