Esempio n. 1
0
    def raiseException(self, message, exception=None, catch=False):
        """
        logs message and raises an exception (since it can be caught higher up and handled)
        and raises it afterwards
        :param exception: subclass of Exception to use for raising
        :param catch: boolean, try to catch raised exception and add relevant info to message
                      (this will also happen if exception is not specified)
        """
        fullmessage = message
        tb = None

        if catch or exception is None:
            # assumes no control by codemonkey
            # lets see if there is something more to report on
            exc, detail, tb = sys.exc_info()
            if exc is not None:
                if exception is None:
                    exception = exc
                # extend the message with the traceback and some more details
                # or use self.exception() instead of self.warning()?
                tb_text = "\n".join(traceback.format_tb(tb))
                message += " (%s)" % detail
                fullmessage += " (%s\n%s)" % (detail, tb_text)

        if exception is None:
            exception = self.RAISE_EXCEPTION_CLASS

        self.RAISE_EXCEPTION_LOG_METHOD(fullmessage)
        raise_with_traceback(exception, message, tb)
Esempio n. 2
0
def logToFile(filename,
              enable=True,
              filehandler=None,
              name=None,
              max_bytes=MAX_BYTES,
              backup_count=BACKUPCOUNT):
    """
    enable (or disable) logging to file
    given filename
    will log to a file with the given name using a rotatingfilehandler
    this will let the file grow to MAX_BYTES and then rotate it
    saving the last BACKUPCOUNT files.

    returns the filehandler (this can be used to later disable logging to file)

    if you want to disable logging to file, pass the earlier obtained filehandler
    """
    handleropts = {
        'filename': filename,
        'mode': 'a',
        'maxBytes': max_bytes,
        'backupCount': backup_count,
    }
    if sys.version_info[0] >= 3:
        handleropts['encoding'] = 'utf-8'
    # logging to a file is going to create the file later on, so let's try to be helpful and create the path if needed
    directory = os.path.dirname(filename)
    if not os.path.exists(directory):
        try:
            os.makedirs(directory)
        except Exception as ex:
            exc, detail, tb = sys.exc_info()
            raise_with_traceback(
                exc, "Cannot create logdirectory %s: %s \n detail: %s" %
                (directory, ex, detail), tb)

    return _logToSomething(
        logging.handlers.RotatingFileHandler,
        handleropts,
        loggeroption='logtofile_%s' % filename,
        name=name,
        enable=enable,
        handler=filehandler,
    )