CHUVASH.eu

CHunky Universe of Vigourous Astonishing SHarepoint :)

Tag Archives: log

Log to ULS using javascript

uls_001

The more javascript code is produced in SharePoint solutions, the more need we have to log information and possible errors to a central logging  place in SharePoint: ULS. This blog post is about logging to ULS from javascript.

For a while ago I read a blog post:

The author @avishnyakov mentions the ability log to ULS from javascript. I want to dive deeper.

ULS.enable = true
ULSOnError("Hello from javascript", location.href, 0);

What this function actually does, is that it calls a web service called _vti_bin/diagnostics.asmx

We can follow the function in the init.debug.js

function ULSOnError(msg, url, line) {
    return ULSSendExceptionImpl(msg, url, line, ULSOnError.caller);
}

ULSOnError invokes ULSSendExceptionImpl:

function ULSSendExceptionImpl(msg, url, line, oCaller) {
    if (Boolean(ULS) && ULS.enable) {
        ULS.enable = false;
        window.onerror = ULS.OriginalOnError;
        ULS.WebServiceNS = "http://schemas.microsoft.com/sharepoint/diagnostics/";
        try {
            ULS.message = msg;
            if (url.indexOf('?') != -1)
                url = url.substr(0, url.indexOf('?'));
            ULS.file = url.substr(url.lastIndexOf('/') + 1);
            ULS.line = line;
            ULS.teamName = "";
            ULS.originalFile = "";
            ULS.callStack = '<stack>\n' + ULSGetCallstack(oCaller) + '</stack>';
            ULS.clientInfo = '<client>\n' + ULSGetClientInfo() + '</client>';
            ULSSendReport(true);
        }
        catch (e) { }
    }
    if (Boolean(ULS) && Boolean(ULS.OriginalOnError))
        return ULS.OriginalOnError(msg, url, String(line));
    else
        return false;
}

ULSSendExceptionImpl invokes ULSSendReport:

function ULSSendReport(async) {
    ULS.request = new XMLHttpRequest();
    ULS.request.onreadystatechange = ULSHandleWebServiceResponse;
    ULS.request.open("POST", ULSGetWebServiceUrl(), async);
    ULS.request.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
    ULS.request.setRequestHeader("SOAPAction", ULS.WebServiceNS + "SendClientScriptErrorReport");
    ULS.request.send('<?xml version="1.0" encoding="utf-8"?>' 
        + '<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">' 
        + '<soap:Body>' 
        + '<SendClientScriptErrorReport xmlns="' + ULS.WebServiceNS + '">' 
        + '<message>' + ULSEncodeXML(ULS.message) + '</message>' 
        + '<file>' + ULSEncodeXML(ULS.file) + '</file>' 
        + '<line>' + String(ULS.line) + '</line>' 
        + '<stack>' + ULSEncodeXML(ULS.callStack) + '</stack>' 
        + '<client>' + ULSEncodeXML(ULS.clientInfo) + '</client>' 
        + '<team>' + ULSEncodeXML(ULS.teamName) + '</team>' 
        + '<originalFile>' + ULSEncodeXML(ULS.originalFile) + '</originalFile>' 
        + '</SendClientScriptErrorReport>' 
        + '</soap:Body>' + '</soap:Envelope>');
}

Alternatives

An alternative way is to create an own handler that is invoked through an ajax request and that implement an own logic for writing logs to ULS. You can see a neat solution provided by Albert Jan-Shot:

Not to be confused with SP.ULS.log

There is another utility function for logging: SP.ULS.log, this function logs messages in a new browser window. In my opinion, it is a substitute for console.log, but the good thing is that you have to manually enable it in order to see:
log-001

 

Logging from an app

If you are developing a sharepoint app, you can log app errors easily by using:

SP.Utilities.Utility.logCustomAppError(
       SP.ClientContext.get_current(), errorMessage);

Very nice intro to sp app logging

clearInterval in Chrome doesn’t work on window blur

If you want to reset all interval jobs when a browser tab is inactive, the best way would be to use clearInterval on window blur. But unfortunately Chrome fires window focus and window blur two times. Here is an embryo to a solution:

var M = window.M || {};
M.counter = 0;
M.focused = true;
M.tick = function() {
  if (M.focused) {
		console.log("tic tac " + ++M.counter);
	}
};
M.start = function(e) {
	console.log("starting...");
	M.focused = true;
};
M.stop = function(e) {
  console.log("stopping...");
  M.focused = false;
};
$(window).on({
	focus: M.start,
	blur: M.stop
});

M.ticker = window.setInterval(M.tick, 1000);

cross browser console.log

console.log is the best tool for debugging javascript. In Firefox Firebug and Chrome Dev Tools you can even log objects which are represented as tree nodes of properties.

If Firebug or Dev Tools in Chrome and IE9 are not opened, all these messages are ignored. But IE8 doesn’t understand console (if Dev Tools are closed) and raises an error:

To avoid these errors, just declare an empty function just for IE8–:

var console = window.console || { log: function() {} };
Microsoft Ajax Library and console.log

In SharePoint and of course in ASP.NET we can use the built-in console tools: Sys.Debug.trace(“some message”);

Do an unsafe update in a unified manner

Recently I talked about a WithWeb-pattern as described in Jonas Nilssons blog where you can isolate the disposal logic in one place. Another thing is to isolate unsafe updates:

public static class SPWebExtension
{
    public static void UnsafeUpdate(this SPWeb web, Action<SPWeb> action)
    {           
        try
        {
            Log.Info("Trying to do an unsafe update on a web: " + web.Title);
            web.AllowUnsafeUpdates = true;
            action(web);
        }
        catch (Exception e)
        {
            Log.Error(e);
        }
        finally
        {
            web.AllowUnsafeUpdates = false;
        }
    }
}

The Log class is my own class which I presented in my previous post.

A simple Log for ULS

Here is a simple log which has been inspired of Android Log. It logs to ULS which you can open with ULSViewer, SharePoint Log Viewer.

using System;
using Microsoft.SharePoint.Administration;

namespace Contoso.Intranet.Portal.Utilities
{
    public class Log
    {
        private static readonly string _CATEGORYNAME = "CONTOSO";
        private static readonly SPDiagnosticsCategory _ERROR_CATEGORY = 
              new SPDiagnosticsCategory(_CATEGORYNAME, TraceSeverity.Unexpected, EventSeverity.Error);
        private static readonly SPDiagnosticsCategory _WARNING_CATEGORY = 
              new SPDiagnosticsCategory(_CATEGORYNAME, TraceSeverity.High, EventSeverity.Warning);
        private static readonly SPDiagnosticsCategory _VERBOSE_CATEGORY = 
              new SPDiagnosticsCategory(_CATEGORYNAME, TraceSeverity.Verbose, EventSeverity.Verbose);
        private static readonly SPDiagnosticsCategory _INFO_CATEGORY = 
              new SPDiagnosticsCategory(_CATEGORYNAME, TraceSeverity.Medium, EventSeverity.Information);

        private static void WriteTrace(SPDiagnosticsCategory category, string message, string trace)
        {
            SPDiagnosticsService.Local.WriteTrace(0, category, category.DefaultTraceSeverity, message, trace);
        }

        public static void Error(Exception ex)
        {
            WriteTrace(_ERROR_CATEGORY, ex.Message, ex.StackTrace);
        }

        public static void Warning(string message)
        {
            WriteTrace(_WARNING_CATEGORY, message, "");
        }

        public static void Verbose(string message)
        {
            WriteTrace(_VERBOSE_CATEGORY, message, "");
        }

        public static void Info(string message)
        {
            WriteTrace(_INFO_CATEGORY, message, "");
        }

    }
}

A possible improvement can be a custom Area. See an example of ThorstenHans on Github: CustomLogger.cs

EDIT: I found an interesting article: How to log to the SharePoint ULS Logs: Clean Debugging and Error Logging broken down into steps written by Philip Stathis.

uls logger

Det finns ett intressant projekt på codeplex: ULS Logger. Är absolut värt att testa.

Sharepoint Log Viewer

Mycket bra verktyg för att debugga din sharepoint applikation är Sharepoint Log Viewer som är Open Source och finns att hämta på codeplex.com

Det går att öppna en logg-fil, det går att köra live monitoring och att exportera. Det sköna är att det är lätt att söka efter correlations-id.

Rekommenderar verktyget!

Discovering SharePoint

And going crazy doing it

Bram de Jager talking Office 365, SharePoint and Azure

My view and thoughts on Productivity and more.

My programming life

and everything in between

SharePoint Development Lab by @avishnyakov

It is a good place to share some SharePoint stories and development practices.

SharePoint Dragons

Nikander & Margriet on SharePoint

RealActivity - Real-time and trustworthy

Blog site of founder, RealActivty - Paul J. Swider

Mai Omar Desouki - Avid SharePointer

Egyptian & Vodafoner - Senior SharePoint Consultant

Cameron Dwyer | Office 365, SharePoint, Outlook, OnePlace Solutions

Office 365, SharePoint, OnePlace Solutions & Life's Other Little Wonders

paul.tavares

Me and My doings!

Share SharePoint Points!!

By Mohit Vashishtha

Jimmy Janlén "Den Scrummande Konsulten"

Erfarenheter, synpunkter och raljerande om Scrum från Jimmy Janlén

SPJoel

SharePoint for everyone

SharePointRyan

Ryan Dennis is a SharePoint Solution Architect with a passion for SharePoint and PowerShell

SharePoint 2020

The Vision for a Future of Clarity

Aharoni in Unicode, ya mama

Treacle tarts for great justice

... And All That JS

JavaScript, Web Apps and SharePoint

blksthl

Mostly what I know about SharePoint - CommunicoCuspis