Tuesday, April 21, 2009

Self-Reporting Reports that Report on their Reporting

I love stupid titles. Maybe because I'm stoopid too. America loves stupid, after all. I was thinking about how I typically weave start/stop times into my scripts. I usually do it to help with diagnosing things in the log files they leave behind. For example, you may notice that I often use a dedicated Sub() to echo status and use a constant variable to toggle it on/off.


Sub DebugPrint(s)
If Verbosity = True Then
Wscript.Echo Now & vbTab & s
End If
End Sub


Well, it's pretty basic obviously, but it can be useful. But what about overall start and stop times?


t1 = Now
'...
' do a bunch of time-consuming junk here...
'...
t2 = Now
Wscript.Echo Abs(DateDiff("s", t2, t1)) & " seconds elapsed"


Taking this a little further, you can easily extend this to define another constant variable to specify the expected elapsed runtime for your script to complete all processing. That way, if the script takes too long, or finishes too quick, you can take action to report that if desired.


' define expected runtime in seconds
Const runtime = 30000

'...
If Abs(DateDiff("s", t2, t1)) > runtime Then
' do something to notify or log the overrun
End If


You could also wrap the runtime variable with a multiplier to pad it with some preferred margin of error. Something like this...


If Abs(DateDiff("s", t2, t1)) > (runtime * 1.50) Then
' do something to notify or log the overrun
End If


The action you take could be sending an e-mail alert, writing and event log entry, writing a log file, running another script, or whatever you can dream up.

The advantages of this approach are that you don't have to employ a separate solution to monitor when scripts take too long. They can handle the notifications themselves. This also makes them more "event-driven" rather than batch-processed, since they will report as the event occurs, rather than waiting to be reported on by another service later. I'm sure that there are drawbacks to this, after all, nothing is a panacea. But this might prove useful for you in some situations. Enjoy!

No comments: