
import logging

from dbglog import dbg


DEBUG = 'DBG'
INFO = 'INFO'
WARNING = 'WARN'
ERROR = 'ERR'
FATAL = 'FATAL'

DBG_LOG_LEVELS = {
    logging.DEBUG: DEBUG,
    logging.INFO: INFO,
    logging.WARNING: WARNING,
    logging.ERROR: ERROR,
    logging.FATAL: FATAL,
}

# Default format
# It contains only information which is not present in DbgLog output.
BASIC_FORMAT = '%(name)s: %(message)s'


def configure(severity=1, level=None, format=BASIC_FORMAT, datefmt=None):
    """
    Configure Python logging to write to DbgLog.

    This function adds a configured `DbgLogHandler` to the root logger.
    It can be used as a shortcut in common cases when detailed
    configuration is not necessary.

    Note that this method does not configure DbgLog itself.

    :param severity: int or dict, for the `DbgLogHandler` constructor
    :param level: sets level of the root logger if not None

    """
    handler = DbgLogHandler(severity)
    formatter = logging.Formatter(format, datefmt)
    handler.setFormatter(formatter)
    root = logging.getLogger()
    root.addHandler(handler)
    if level is not None:
        root.setLevel(level)


class DbgLogHandler(logging.Handler):
    """
    A handler class which writes logging records to DbgLog.
    """

    def __init__(self, severity):
        logging.Handler.__init__(self)
        if isinstance(severity, (int, long)):
            self.severities = {'': severity}
        else:
            self.severities = severity

    def emit(self, record):
        """
        Emits a record.

        Logs the record using the DbgLog library.

        """
        try:
            severity = self.getDbgLogSeverity(record)
            if not severity > 0:
                return
            level = self.getDbgLogLevel(record)
            if not level > 0:
                return
            kwargs = {level: severity}
            # Do not format message if it wont be logged.
            if not dbg.checkLevel(**kwargs):
                return
            msg = self.format(record)
            location = (record.filename, record.funcName, record.lineno)
            dbg.log(msg, location=location, **kwargs)
        except (KeyboardInterrupt, SystemExit):
            raise
        except:
            self.handleError(record)

    def getDbgLogLevel(self, record):
        """
        Returns name of DbgLog level.

        Maps a standard logging level set to a `logging.LogRecord`
        instance to one of 'FATAL', 'ERR', 'WARN', 'INFO' and 'DBG'.

        """
        level = record.levelno
        try:
            return DBG_LOG_LEVELS[level // 10 * 10]
        except KeyError:
            return FATAL if level > logging.FATAL else 0

    def getDbgLogSeverity(self, record):
        """
        Returns severity for DbgLog.

        Maps a logger name set to a `logging.LogRecord` instance
        to a severity number from 1 to 4 (inclusive).

        """
        severities = self.severities
        name = record.name or 'root'
        while True:
            try:
                return severities[name]
            except KeyError:
                pass
            try:
                name = name[:name.rindex('.')]
            except ValueError:
                if not name:
                    return 0
                name = ''

@@ -2992,32 +2992,8 @@
 ot'%0A
-        while True:%0A    
     
@@ -2993,36 +2993,32 @@
 t'%0A        try:%0A
-    
             retu
@@ -3041,28 +3041,24 @@
 me%5D%0A        
- 
-   
 except KeyEr
@@ -3078,16 +3078,56 @@
     
-    
 pass
+%0A        prefix = name%0A        while prefix:
 %0A   
@@ -3160,25 +3160,31 @@
     
-name = name%5B:name
+prefix = prefix%5B:prefix
 .rin
@@ -3244,20 +3244,19 @@
     
-if not name:
+prefix = ''
 %0A   
@@ -3260,32 +3260,37 @@
             
+try:%0A
         
 return 0%0A   
@@ -3281,16 +3281,117 @@
     
-return 0
+        severity = severities%5Bprefix%5D%0A            except KeyError:%0A                continue%0A            else:
 %0A   
@@ -3407,14 +3407,81 @@
     
+severities%5B
 name
+%5D
  = 
-''
+severity%0A                return severity%0A        return 0
 %0A

Optimize logging - cache severities for known loggers.