__rcs_id__='$Id: Logger.py,v 1.5 2002/03/21 05:13:57 zen Exp $'
__version__='$Revision: 1.5 $'[11:-2]

from DocumentTemplate.DT_Util import *
from DocumentTemplate.DT_String import String
import string,sys
import zLOG

LoggerError = "Log Tag Error"

# Perhaps this map should be moved to zLog.py? 
severities = {
    'BLATHER':	zLOG.BLATHER, 
    'INFO': 	zLOG.INFO,
    'PROBLEM':	zLOG.PROBLEM,
    'WARNING':  zLOG.WARNING,
    'ERROR':	zLOG.ERROR,
    'PANIC':	zLOG.PANIC,
    }

# Add newer severities without insising we run a newer Zope
try: severities['TRACE'] = zLOG.TRACE
except KeyError: pass
try: severities['DEBUG'] = zLOG.DEBUG
except KeyError: pass
try: severities['WARNING'] = zLOG.WARNING
except KeyError: pass

invalidseverity = 'Invalid Severity'

class LogTag:
    '''Send a message to Zope's logging system. See README.txt for
       details.'''

    name='log'
    blockContinuations=('logdetail',)

    def __init__(self, blocks):

	tname, args, section = blocks[0]

	args = parse_params(args, severity=None, subsystem=None, exception=0)

	has_key=args.has_key

	if not has_key('severity'): 
	    args['severity'] = 'INFO'
	else:
	    args['severity'] = string.upper(args['severity'])
	    if not severities.has_key(args['severity']):
		raise invalidseverity, (
		    'An invalid severity (%s) was given' % args['severity'])

	if not has_key('subsystem'):
	    args['subsystem'] = 'DTML'

	self.args = args
	self.sectionSummary = section

	if len(blocks) > 1:
	    self.sectionDetail = blocks[1][2]
	else:
	    self.sectionDetail = None

    def render(self,md):
	subsystem = self.args['subsystem']
	severity  = severities[self.args['severity']]
        try:
            if hasattr(md,'this'):
                summary = self.sectionSummary(md.this,md)
            else:
                # This fixes a bug, but I can't decode cDocumentTemplate.c
                # enough to work out why
                summary = self.sectionSummary(None,md)
        except:
            zLOG.LOG(subsystem,zLOG.ERROR,
                'Exception raised rendering DTML in dtml-log tag',
                error=sys.exc_info(),reraise=1)

	detail = ''
        try:
            if self.sectionDetail is not None:
                if hasattr(md,'this'):
                    detail = self.sectionDetail(md.this,md)
                else:
                    detail = self.sectionDetail(None,md)
        except:
            zLOG.LOG(subsystem,zLOG.ERROR,
                'Exception raised rendering DTML in dtml-logdetail',
                error=sys.exc_info(),reraise=1)
        if self.args.has_key('exception'):
            zLOG.LOG(subsystem,severity,summary,detail,error=sys.exc_info())
        else:
            zLOG.LOG(subsystem,severity,summary,detail)

	return ' '

    __call__ = render

String.commands['log'] = LogTag

