A JavaScript frontend logging system that logs to our backend? - javascript

We have an established logging system for our server-side services. Specifically, our Django project makes heavy use of the Python logging module, so call calls to logger.info(), logger.warn() and logger.error() get picked up by our centralized logging system.
I would like an equivalent on our frontend, and I've got a few ideas:
There would be some sort of custom logging object exposed via JavaScript that would send messages to backend via an XmlHttpRequest.
I'd like to have equivalent logging levels on the client-side: debug, info, warning and error.
When we're developing locally (debug mode), I'd like those logging messages to be logged to the browser/Firebug console via console.log().
In production, debug messages should be dropped completely.
I recall seeing a way to capture all uncaught JavaScript exceptions, so these should be logged at the error level.
We're already using Google Analytics event tracking, and it'd be nice for whatever system we create to tie into that somehow.
Is this a good idea? How would you do this? Are there existing solutions?
(FWIW, we're using jQuery on the frontend.)
Update: Simplified question here: https://stackoverflow.com/questions/1423267/are-there-any-logging-frameworks-for-javascript

First, I wrote and maintain log4javascript, so I'm declaring my interest up front. I also use it every day in my work, so I have some experience of it as a user. Here's how I would deal with your questions, specifically relating to log4javascript:
Use log4javascript's AjaxAppender for server logging;
debug, info, warning and error are all supported, as well as trace and fatal;
Use a BrowserConsoleAppender to log to FireBug or the native browser console;
If you don't want to remove all debug logging calls from you production code, you can either adjust your logger's threshold (using log.setLevel(log4javascript.Level.ERROR), for example, which will suppress all log calls with priority less than ERROR). If you want to suppress all logging calls, you can drop in a stub version of log4javascript in your production code.
You'll need to write a bit of code to do this using window.onerror. Something like window.onerror = function(msg, file, line) { log.error("Error in " + file + " on line " + line + ": " + msg); }
I'm not sure how you want to tie in with Google Analytics. log4javascript has no particular support for it.

The idea sounds good here. Just be aware of what exactly it is you are looking to log client-side and have at it.
I would recommend using log4javascript for logging. The log4 api is pretty straight foward.

Here is another question from here on SO about this very issue.
Some recommendations are: log4js, log4javascript, and Blackbird.
FWIW, log4js was the accepted answer there. I don't have experience with any of these platforms, so I can't really recommend one over the other.

Related

Azure service bus not receiving messages

I'm using Azure service bus to send messages across containers in my K8s setup. Implementation of service that receives message is done in Node.js.From the doc page, here is the code I'm using to receive the messages.
serviceBusService.receiveQueueMessage('feedback', function(error, receivedMessage) {
if (!error) {
// Message received and deleted
console.log(receivedMessage);
//..
}
});
Everything works as expected for the first time but the messages are not received for the second time. It works as expected when the code snippet is kept inside the setInterval block. Which seems not the intended way of doing this.
Any ideas what could be wrong?
I have not used the js library for ServiceBus client, but the .NET library that has it seems similar methods. So if the js versjon works the same way, so then it receives only one message and you have to continue yourself.
In .Net library there are generally two ways:
You write your own while loop with whatever you think necessary
You use RegisterMessageHandler that seems to be absent from js library
The option number 2 generally does the same and starts the while loop inside the pump so that you don't have to implement it yourself.
You can take a look here on how the while loop is implemented and do something similar to it in js.
Like Mikhail Shilkov has mentioned previously in the comments, I suspect it only receives one message and I'd also recommend using the AMQP libraries.
I know this is a late reply, but just in case someone is running into issues, refer to the links below.
Version 7.0.0 of #azure/service-bus(based on AMQP) has been recently published.
#azure/service-bus - 7.0.0
Samples for 7.0.0
Guide to migrate from #azure/service-bus v1 to v7

Browser.ExecScript() stopped working after updating windows

I've set up a simple testbed for WatiN (ver 2.1) which reads:
var browser = new IE();
browser.GoTo("http://www.google.co.il"); // webpage doesn't matter really
browser.RunScript("alert(123)");
This works only if KB3025390 is not installed. Installing it breaks the above test with an UnAuthorizedAccessException which has HRESULT set to E_ACCESSDENIED. What gives? Is there any workaround?
Update: Using IWebBrowser2.Navigate2 along with "javascript:console.log(123)" type of scripts works however
it makes me feel uneasy using such a backchannel
the scripts run through this back-channel of .Navigate2() may only have a max length of about 2070 chars (give or take) otherwise they get forcibly truncated to this length leading to javascript errors upon attempting to run them
using .Navigate2(), even with the most trivial script, will clog the ready state of Internet Explorer for good in the sense that it will be set to READYSTATE_LOADING without any hope of getting rid of it. In simple terms this means that once you use this hack, you either have to perform every single subsequent operation in WatiN in a "dont-wait-for-webpage-to-load" fashion (GoToNoWait, ClickNoWait etc) lest your code freezes upon waiting for the browser to turn back to READYSTATE_COMPLETE (which will never come about ofcourse as already mentioned).
there appears to be a much broader issue here in the sense that I can't even access the properties of an IHtmlWindow2 object p.e. window.document throws an unauthorized exception again making it virtually impossible to transfer over to the C# world the return-values of the scripts I'm running (using Expando etc) for documents other than window.top.document (for the window.top.document window there is IWebBrowser2.Document which does the trick)
Update#2: The folks over at the selenium project have also noticed this issue:
https://code.google.com/p/selenium/issues/detail?id=8302
A bug report has been created as well:
https://connect.microsoft.com/IE/feedback/details/1062093/installation-of-kb3025390-breaks-out-of-process-javascript-execution-in-ie11
Update#3: IHTMLWindow2.setInterval and IHTMLWindow2.setTimeout also throw UnauthorizedAccess exceptions. These methods are not marked as deprecated in:
http://msdn.microsoft.com/ko-kr/library/windows/desktop/aa741505%28v=vs.85%29.aspx
yet they have wounded up suffering from the same cutbacks all the same.
Update#4: I gave the approach recommended in this post a shot:
https://stackoverflow.com/a/18546866/863651
In order to dynamically invoke the "eval" method of the IHTMLWindow2 object (or any other method really). Got the same "System.UnauthorizedAccessException" as above. So no joy here either.
Microsoft recommends using "eval" over "execscript" however after the above experiment I suspect that they are refering to accessing "eval" only from within the browser.
As far as I can tell thus far, when it comes to the full-fledged IE11+ using "eval" out-of-process (via COM) appears to have been completely prohibited along with any other function-invocation of the window object, the only exception being the back-channel of the .Navigate2() mentioned above.
It turns out Microsoft eventually backpedaled on its decision to kill off .execScript at COM-level. Just install the latest updates for Windows including kb3025390: One of the updates for IE that came after kb3025390 brings back .execScript functionality at COM-level
Note, however, that .execScript is not accessible through IE's javascript anymore. In that context it's gone for good.
fyi: this one is also not working
ieInstance.Document.Script.<methodNameString>(<commaSeperatedParameterString>)
try this worked for me at some places but not all places
ieObject.Navigate "javascript:<methodNameString>(<commaSeperatedParameterString>)", Null, "_parent"
or
ieObject.Navigate2 "javascript:"<methodNameString>(<commaSeperatedParameterString>)", Null, "_parent"
now trying to find out solution using eval
I have found a way around the problem of an update installing automatically. You can just create a simple batch file with following content.
{code}
#echo off
wusa /uninstall /kb:3025390/quiet /norestart
END
{code}
Then go to task scheduler, create a new task for this batch file to run every one hour or day as per your requirements. Add it as a system task so it runs in the background and does not affect the running automations.

Degrees of JS vulnerability

Never trust the client. It's my coding mantra. All javascript can, with enough effort, be overwritten or compromised. The thing I want to understand is how.
Let's say I wrote a function checkStep() for a game - each time the player moves one space, it polls the server to check for any events: HP regeneration, enter random battle, move to next map, etc. I asked myself "self, how would I go about rewriting or disabling this function?" Research turned up some conflicting results. Some sources say functions can be directly redefined from the console, others say it would be a much more involved process.
My question is this: what would a player have to do to rewrite or disable my checkStep() function? Can they simply redefine it from the console? Would they have to rip, modify, and re-host my code? How would you do it?
Please note, I'm not asking how to make this function secure.
The first person to leave an answer/comment along the lines of "you
can try minifying it, but it still wont be secure" or "put in some
server-side checks" is getting bludgeoned with a semicolon, as an
example to the rest.
You could use a web debugging proxy like Fiddler to do this for your local machine. Programs like this allow you to intercept content you download and fiddle with it. So you could write a new version of the function, then use the program to replace it with your version when the file is downloaded from the server. Then, for your local machine, the code would run with the new function in place. The web session manipulation page on the Fiddler site has a few more details.
There is no reason to use any Javascript or browser a even.
If a normal user can use their browser to play the game then any user can use any program to communicate with the server and send it anything they want. The server is not able to know if someone is using a browser to connect to it or not.
This applies to anything. A game server doesn't know if the user is connecting to it through the official game client. Since the official game is closed source it would be easy to fall into trusting it even though it is possible to reverse engineer the protocols used and use anything to connect to the server.
Complex things like creating a malicious game client, or using a proxy to alter content before it makes it to the browser are technically valid points, however that seems like a lot of effort for something which is very simple to do.
var checkStep = function() {
... // your original function
}
// later on
checkStep = function() {
alert('foo');
}
It is perfectly valid in JavaScript to change what function a variable holds. Any function you define can be redefined on the client side. This can be done by other script files loaded by the browser which use conflicting variable names, scripts injected via XSS, or by the user bringing up the console.

How to run jslint on the client?

For testing purposes, obviously not for production. What is the best way to do this?
Googling I found this tutorial, and of course the project on github.
For starters which files do I need to run:
// removed
and is there an API reference. I see there is a large comment block in jslint.js that seems to server this purpose but was wondering if there is something easier to read.
Because the client has no file access, I was planning on ajaxing the code in to get its contents.
Please never the mind, on why I want to do this on the client.
If you include the JSLint script you will have access to a single global variable, JSLINT. You can invoke it with a string and an optional map of options:
var valid = JSLINT(code, options);
The result will be true or false, depending on whether the code passed the check based on the provided options.
After this call you can inspect the JSLINT.errors property for an array of warnings, if any.
This is precisely what I have done to build JSLint integration into the editor in the articles on http://jslinterrors.com.
Have you looked at http://jshint.com/ ? Source is available here: https://github.com/jshint/jshint/
The browser bundle is available here: http://jshint.com/get/jshint-2.1.10.js and the docs describe how to call it (http://jshint.com/docs/)

Robust Javascript Exception Handling

I am developing a DHTML/Javascript application which relies on some advanced features (DOM manipulation, AJAX, Flash communication, and more). I'm very concerned about functionality -- if problems occur, even after the application is deployed, I want to make sure I know why and how to fix them -- and also, I want to make sure the user is able to continue using the application, possibly with reduced functionality if the exception was severe.
I currently have a logging and exception handling system built whereby functions can generate logs, and if an exception is caught, all logs are emailed to me. The system works well but I'd like to make it more robust. I'm looking for suggestions.
One idea I have is to wrap the body of every javascript function in a try/catch block and upon catching an exception, log the name of the function and then throw the error to the global handler. But that's a lot of code just to track down the function the exception occurred in.
Any ideas to make runtime exceptions easier to find and reproduce?
Rather than dealing with adding N try/catch blocks to N functions, it might be easier to use the window.onerror event.
JavaScript Kit has a series of examples you could use. Especially the 3rd:
window.onerror = function (msg, url, line) {
alert('Error message: ' + msg + '\nURL: ' + url + '\nLine Number: ' + line);
return true;
}
If you'd prefer a stack trace, you might check out Eric Wendelin's (or Luke Smith's update). It's one of the few I know of that attempts to work cross-browser.

Categories

Resources