#
# CastPodder console logging module
# Copyright (c) 2005-2006 Scott Grayban and the CastPodder Team
#
# ConsoleFormatter and ConsoleLogRecordProxy work together to alter the 
# default output format of the logging module. Current functionality 
# includes wrapping output and not bothering with a log level indicator 
# if the record has INFO level. 
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
# $Id: conlogging.py 96 2006-07-10 19:50:46Z sgrayban $

import logging
import textwrap

class ConsoleLogRecordProxy(logging.LogRecord):
    "A LogRecord that wraps lines for console output, etc."
    
    def __init__(self, record, wrap):
        "Initialise the `WrappingLogRecordProxy`."
        self.__record = record
        self.__wrap = wrap
        
    def getMessage(self):
        "Return an adjusted version of the original record's message."
        r = self.__record
        msg = r.getMessage()
        if r.levelno != logging.INFO:
            msg = "%s: %s" % (r.levelname, msg)
        if self.__wrap: 
            msg = '\n'.join(textwrap.wrap(msg, width=78))
        return msg
    
    def __str__(self):
        "Convert this record to a string."
        return self.__record.__str__()
    
    def __getattr__(self, key):
        "Shadow attributes on the original record."
        return getattr(self.__record, key)

class ConsoleFormatter(logging.Formatter):
    """Console log formatter. 
    
    Converts records to WrappingLogRecordProxy records."""
    
    def __init__(self, *a, **kw): 
        "Initialise the `ConsoleFormatter`."
        if kw.has_key('wrap'):     # if there's a wrap= argument
            self.wrap = kw['wrap'] # steal it
            del kw['wrap']         # and delete it
        else: 
            self.wrap = False
        logging.Formatter.__init__(self, *a, **kw)
        
    def format(self, record):
        "Format a record by wrapping it."
        record = ConsoleLogRecordProxy(record, self.wrap)
        return logging.Formatter.format(self, record)
