If you are developing a server-side script such as a Create Script, Validate Script or Table Level Script, it is often useful to write debugging information to a log.  Jeff has blogged about a technique for doing this using the Scripting.FileSystemObject.

I'd like to share with you a very simple function that you can use to write to the CRM SQL logs without needing to set up file permissions or instantiate an external object:

function log(message) {try{CRM.CreateQueryObj('/* '+message+' */').SelectSql();}catch(e){}}

Use this function like this:

log('Hello World!');

This will generate a line in the SQL logs like this:

Oct 1 2009 19:27:51.590 37040 28700 3 fqopen,time,sql 0 /* Hello World! */

Note that the default filtering for SQL logs is to only log errors, so by default this log would not be seen.  What if you want it to be always seen no matter what the logging level?  Well we could do that by putting a benign error into the SQL.

For example this SQL statement will cause an error:

/* Hello World!

You will get this error back from SQL: Missing end comment mark '*/'

Here is a modified version of the function which introduces the error if a second parameter is passed:

function log(message, error) {try{CRM.CreateQueryObj('/* '+((error)?message:message+' */')).SelectSql();}catch(e){}}

Now we can do this:

// This will show up in the logs no matter what:
log('This will cause an error',1);

// This will only show up if you have full SQL logging turned on:
log('Of no consequence');