Function to create logs that CMTrace can read

I like to log things when I code, especially while debugging. I also like how I can watch logs real time with CMTrace, so I wrote a function that writes out the log entries in a format CMTrace can read. To use it, at the beginning of the script you are writing, these are the parameters to add for logging.

The LogLevel parameter specifies what level of entries to log. The thing to remember is that you set the level of each entry when you call the script.  So you can set the LogLevel to 1 when debugging and 2 or 3 when running the final script. The default is 2.

The LogFileDir parameter specifies the directory where the log file will be put, the default is C:\Temp.

The ClearLog parameter will delete the existing log file in the LogFileDir if it exists.

This portion of the script sets the log file name to LogFileDir\ScriptName.log, and clears the logfile if the flag is set.

And here’s the function! When you call the function, you pass one required and two optional paramemters. The first, and mandatory, parameter is the entry. This is the information to be logged.

The second parameter is the loglevel, if left out, it will be 1. If you put 2 or 3 it will be registered as warning and highlighted yellow or critical and highlighted red respectively when CMTrace displays the log.

The third parameter is component. I generally put the function name or something that identifies what component in the script is generating the log.

You may have seen this is some of my previous scripts but have added the ClearLog switch.

You can see here, the component changes on the last three lines. That is where the function is calling the log entry.


Hope you can use this little snippet in your code! In parting, here is an example script with all the pieces in place

%d bloggers like this: