
"""A very rudimentary logging facility."""

import sys

loglevel = 5
loggers = []

levelnames = [ '', 'CRITICAL', 'SERIOUS', 'BUG', 'PROBLEM', 'EVENT',
		'WEIRD', 'INFO', 'DEBUG', 'DEBUG' ]

def add_logger( logger ):
    """Add a new function that will receive logging events.
    
    logger should be a function accepting two arguments: the importance
    level and the message."""
    loggers.append( logger )

def log( level, msg ):
    """Inform interested parties about noteworthy events.

    level is the importance of an event: the lower the number, the
    higher the importance.  Levels 1--2 are for critical conditions;
    3--4 for bugs or other abnormal behaviour; 5 for ordinary events
    worth logging even in production use; 6 for abnormal conditions that
    don't matter and 7--9 for informational / debugging messages."""

    cause = sys._getframe( 1 ).f_code.co_name
    if level <= loglevel:
	sys.stderr.write( "<%s> %s: %s\n" % ( levelnames[level], cause, msg ))
    for lgr in loggers: lgr( level, cause, msg )

def log_uncaught_exception( level ):
    """Log an uncaught exception.

    This function is meant to be used from your application's highest
    level to log exceptions that 'should not have happened' but which
    you can't afford to let terminate your application.  level is the
    logging level, and should naturally imply relatively high
    importance."""

    typ, val, trace = sys.exc_info()
    log( level, "%s(%r)" % ( typ, val ))
    log( level, "Backtrace:\n%s" % trace )

