Requirement: Add client side logging and send it to server. Devs in server should be able to enable or disable this logging functionality.
My Approach: I have created a ASP.NET WebAPI project, where i have created a POST method to write log data to a local file. So, that i can add and monitor client side logs.
Now, From the client side i am not able to call the post method. I have used log4javascript. There i got AjaxAppender to send request to server.
JS code using log4javascript:
// Create the logger
var log = log4javascript.getLogger();
// Create a AjaxAppender with default options
var ajaxAppender = new log4javascript.AjaxAppender('http://localhost:59132/api/log');
// If you want to send JSON
var jsonLayout = new log4javascript.JsonLayout();
// Add configuration for ajaxAppender
//ajaxAppender.setThreshold(log4javascript.Level.ERROR); // Sets the appender's threshold. Log messages of level less severe than this threshold will not be logged.
//ajaxAppender.setBatchSize(10); // Sets the number of log messages to send in each request.
//ajaxAppender.sendAll(); // send all remaining messages on window.beforeunload()
ajaxAppender.addHeader("Content-Type", "application/json");
ajaxAppender.setLayout(jsonLayout);
// Adds the given appender
log.addAppender(ajaxAppender);
// Log message
log.debug("Debug");
log.info("Info");
log.warn("Warning");
log.error("Error");
log.fatal("Fatal");
Server Side Code:
[HttpPost]
public void Post([FromBody]List<string> value)
{
string path = AppDomain.CurrentDomain.BaseDirectory + "Log.txt";
foreach(string s in value)
{
using (StreamWriter writetext = new StreamWriter(path, true))
{
writetext.WriteLine("Log: " + s.ToString() + " " + DateTime.Now);
}
}
}
Moreover, Using jQuery Ajax i am able to send log messages, but i don't think i should implement this in my project, because i am storing the logs in an array and I don't have any configuration set(i.e. I will not be able to enable and disable JS logging feature).
JS Code using jQuery Ajax:
$(document).ready(function (){
var logArr = [];
logArr.push("Error - XYZ " + "URL: " + window.location.href);
logArr.push("Info - PQRS " + "URL: " + window.location.href);
logArr.push("Warning - MNOP " + "URL: " + window.location.href);
sendError(logArr)
});
function sendError(message) {
$.ajax({
url: "/api/log",
type: 'POST',
async: true,
data: JSON.stringify(message),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function () {
console.log("Success");
},
error: function (e) {
console.log("Failure " + e.message);
}
});
}
Can log4JS, JSNLog can resolve this? Please, guide me here.
NOTE: We will not be using any error tracking tool like: errlytics, rollbar etc. As they are paid.