Write to Event Viewer while Testing Automation Snippets or Custom Order Rules

When creating Python code for Select, it is difficult to diagnose exactly what went wrong if there is any failure. The code below shows how to write messages to the System Event Viewer to help debug them.

It is extremely important that it is removed from production code. If not, the increased CPU loading could greatly reduce the system responsiveness. The additional event log messages will ultimately be found as the reason and you will have to remove it anyway. Got it? Good.

# Required namespace for Trace class.
import System.Diagnostics as SD

# Write messages to Event Viewer.
x = 10
SD.Trace.TraceWarning('X = ' + str(x))
SD.Trace.TraceWarning('Got to step 3')
SD.Trace.TraceWarning('Type of X: ' + str(type(x)))

Use the messages to indicate the value of variables, as statements to indicate where you are in the logic, or display the variable type. It will generate three separate event log warnings with the following messages:

X = 10
Got to step 3
Type of X: <type 'int'>

Extra Credit

Of course if you want to see the variable type as a pretty string, you can do this instead. Is it better? Who cares. It may be cleaner if you need to include it in a string with other information.

SD.Trace.TraceWarning('Type of X: ' + type(x).__name__)

Results in:

Type of X: int

On occasion, I have had to wrap code I was writing inside a try/except block to get additional information about snippet code throwing exceptions. This code will display information for the exception and any inner exceptions. Then it will throw the original exception to Select for handling.

from System import *

# Required namespace for Trace class.
import System.Diagnostics as SD

try:
    # Insert user code here...
        
except Exception as e:
    s = 'Name of python snippet' # Insert identifying name for snippet.
    s += '\nException: ' + str(e)
    s += '\nMessage: ' + str(e.Message)
    s += '\nSource: ' + str(e.Source)
    s += '\ndir: ' + str(dir(e))
    
    # Loop and print all inner exceptions.
    inner = e.InnerException
    while inner:
        s += '\n===================================== INNER EXCEPTION ====================================='
	    s += '\nException: ' + str(inner)
	    s += '\nMessage: ' + str(inner.Message)
	    s += '\nSource: ' + str(inner.Source)
	    s += '\ndir: ' + str(dir(inner))
        inner = inner.InnerException
    
    # Write event view warning message then throw exception back to Select for handling.
    SD.Trace.TraceWarning(s)
    raise