Thursday, May 21, 2009

Silverlight Logging Extension Method

Most of you will know that a Silverlight application runs in the Browser and Console.WriteLine() doesn’t work. During the development process you could use System.Diagnostics.Debug.WriteLine() to write messages to Visual Studio’s Output window. But what if an application is deployed and no Visual Studio is nearby and you just want simple Console output and not a logging framework like Clog, where a web service is involved? Or don’t want to use Visual Studio’s Output window?
The answer is simple if you are using Firefox with the Firebug add-on or Internet Explorer 8: Use the console.log mechanism and write your debug output to the Browser’s debug console.

Here's a simple extension method, which logs an object to the console.log:

17 comments:

I modified the code slightly to check for the existence of console and console.log. That way it will quietly fail (i.e., it won't throw an InvalidOperationException on Eval) if it's running in IE8 with the "Developer Tools" window closed or in earlier versions of IE.

Just to note that in case you are using Google Chrome without FireBug lite for chrome (which I just installed) the code is likely to crash during the consoleLogFunction.InvokeSelf, due to a System.InvalidOperationException exception.

You could do the Try/Catch trick to surround the call, unless there is a better test you could perform instead.Vincent Thavonekham.

I just wanted to share my workaround for the Chrome exception when Invoking console.log.

My solution creates a user defined javascript function containing the call to console.log and passing the message as a parameter. I then call eval.call (window.execScript in IE) to load the function into global scope and then I can invoke my custom function instead of console.log directly. This works perfectly in Chrome.

Really nice stuff. I am trying to use your logger but it's working on IE9 but not on Chrome... By any chance, do you have a workaround to make it work on Chrome too? or at least make it fail silently on Chrome?