#!/usr/bin/python
"""Utility functions for debugging output."""


#from configuration import *
import cgi, os, sys, traceback


# Debugging severity levels
TRACE = 0
VERBOSE = 1
INFO = 2
WARNING = 3
ERROR = 4
FATAL = 5
leveltext = ['TRACE', 'VERBOSE', 'INFO', 'WARNING', 'ERROR', 'FATAL']

# Components of stack trace (indices to tuple)
FILENAME = 0
LINENO = 1
FUNCNAME = 2
#SOURCELINE = 3			# Not used


# Debugging output styles
#ENABLE_DEBUGGING_OUTPUT = 'comment'	# HTML comment
#ENABLE_DEBUGGING_OUTPUT = 'display'	# HTML preformatted text
#ENABLE_DEBUGGING_OUTPUT = 'plaintext'	# Plain text
ENABLE_DEBUGGING_OUTPUT = None			#

# Debugging output level to use
DEBUGGING_OUTPUT_LEVEL = TRACE
#DEBUGGING_OUTPUT_LEVEL = VERBOSE
#DEBUGGING_OUTPUT_LEVEL = WARNING


#######################################
def DEBUG (level = TRACE, text = '...'):
	"""Conditional output of debugging text."""

	if not ENABLE_DEBUGGING_OUTPUT:		return
	if level < DEBUGGING_OUTPUT_LEVEL:	return

	trace = traceback.extract_stack ()[-2]
	printinfo = cgi.escape ('%7s:  %16s () [%15s : %i]\n\t\t\t%s' \
		% (leveltext[level], trace[FUNCNAME],
			os.path.split (trace[FILENAME])[-1],
			trace[LINENO], text))

	if (ENABLE_DEBUGGING_OUTPUT == 'display'):
		# Print as preformatted HTML text
		print '\n<pre>%s</pre>\n' % printinfo
	elif (ENABLE_DEBUGGING_OUTPUT == 'comment'):
		# Print as HTML comment
		print '\n<!-- %s -->\n' % printinfo
	elif (ENABLE_DEBUGGING_OUTPUT == 'plaintext'):
		# Print as plaintext
		print '%s\n' % printinfo

	return
#end DEBUG
	
