示例#1
0
    def _setup(self, app_obj):
        super(PmLogHandler, self)._setup(app_obj)
        if self._meta.namespace is None:
            self._meta.namespace = self.app._meta.label

        self.backend = Logger(self._meta.namespace)

        # hack for application debugging
        if is_true(self.app._meta.debug):
            self.app.config.set('log', 'level', 'DEBUG')
            
        # Mainly for backwards compatibility since Logger level should
        # be NOTSET (level 0). Output level is controlled by handlers
        self.set_level(self.app.config.get('log', 'level'))
        
        # clear loggers?
        if is_true(self._meta.clear_loggers):
            self.clear_loggers()
            
        # console
        if is_true(self.app.config.get('log', 'to_console')):
            self._setup_console_log()
        
        # file
        if self.app.config.get('log', 'file'):
            self._setup_file_log()
        # nested setup
        self.backend.handlers.append(logbook.NullHandler(bubble=False))
        self.log_setup = logbook.NestedSetup(self.backend.handlers)
        with self._console_handler.applicationbound():
            self.debug("logging initialized for '%s' using PmLogHandler" % \
                           self._meta.namespace)
示例#2
0
    def _setup(self, app_obj):
        super(PmLogHandler, self)._setup(app_obj)
        if self._meta.namespace is None:
            self._meta.namespace = self.app._meta.label

        self.backend = Logger(self._meta.namespace)

        # hack for application debugging
        if is_true(self.app._meta.debug):
            self.app.config.set('log', 'level', 'DEBUG')

        # Mainly for backwards compatibility since Logger level should
        # be NOTSET (level 0). Output level is controlled by handlers
        self.set_level(self.app.config.get('log', 'level'))

        # clear loggers?
        if is_true(self._meta.clear_loggers):
            self.clear_loggers()

        # console
        if is_true(self.app.config.get('log', 'to_console')):
            self._setup_console_log()

        # file
        if self.app.config.get('log', 'file'):
            self._setup_file_log()
        # nested setup
        self.backend.handlers.append(logbook.NullHandler(bubble=False))
        self.log_setup = logbook.NestedSetup(self.backend.handlers)
        with self._console_handler.applicationbound():
            self.debug("logging initialized for '%s' using PmLogHandler" % \
                           self._meta.namespace)
示例#3
0
    def _setup(self, app):
        super()._setup(app)
        if self._meta.namespace is None:
            self._meta.namespace = self.app._meta.label

        self.backend = logging.getLogger(f"spiral:app:{self._meta.namespace}")

        # hack for application debugging
        if is_true(self.app.debug):
            self.app.config.set(self._meta.config_section, "level", "DEBUG")

        level = self.app.config.get(self._meta.config_section, "level")
        self.set_level(level)

        LOG.debug("logging initialized for '%s' using %s" %
                  (self._meta.namespace, self.__class__.__name__))
示例#4
0
    def _process_parsed_arguments(self):
        if self.app.log and not getattr(self.app._meta, 'log_level', None):
            # hack for application debugging
            if is_true(self.app._meta.debug):
                self.app.config.set(self._meta.config_section, 'level',
                                    'DEBUG')
            else:
                if not self.app.pargs.log_level is None:
                    self.app.config.set(self.app.log._meta.config_section,
                                        'level',
                                        string.upper(self.app.pargs.log_level))
            level = self.app.config.get(self.app.log._meta.config_section,
                                        'level')
            level = level.upper()
            if level not in self.app.log.levels:
                level = 'INFO'
            ilevel = getattr(logging, level)

            if self.app.log.backend.level != ilevel:
                self.app.log.set_level(level)
            setattr(self.app._meta, 'log_level', level)
示例#5
0
    def _setup_console_log(self):
        """
        Add a console log handler.
        """
        namespace = self._meta.namespace
        to_console = self.app.config.get(self._meta.config_section,
                                         "to_console")
        if is_true(to_console):
            console_handler = logging.StreamHandler()
            console_format = self._get_console_format()
            formatter = self._get_console_formatter(console_format)
            console_handler.setFormatter(formatter)
            console_handler.setLevel(getattr(logging, self.get_level()))
        else:
            console_handler = NullHandler()

        # FIXME: self._clear_loggers() should be preventing this but its not!
        for i in logging.getLogger(f"spiral:app:{namespace}").handlers:
            if isinstance(i, logging.StreamHandler):
                self.backend.removeHandler(i)

        self.backend.addHandler(console_handler)
示例#6
0
def hook_pre_setup(app):
    if os.path.isdir('./config'):
        ext = app._meta.config_extension
        label = app._meta.label
        path = os.path.join('.', 'config', '%s%s' % (label, ext))
        if app._meta.config_files is None:
            app._meta.config_files = [
                os.path.join('/', 'etc', label, '%s%s' % (label, ext)),
                os.path.join(fs.HOME_DIR, '.%s%s' % (label, ext)),
                os.path.join(fs.HOME_DIR, '.%s' % label, 'config'),
            ]
            # app._meta.config_files = [path]
        app._meta.config_files.append(path)
    else:
        app.log.debug('There is no ./config in {}'.format(os.path))
    try:
        if 'CEMENT_FRAMEWORK_LOGGING_DEBUG' in os.environ.keys():
            if is_true(os.environ['CEMENT_FRAMEWORK_LOGGING_DEBUG']):
                cement.core.foundation.LOG = minimal_logger(
                    cement.core.foundation.LOG.namespace, True)
                cement.ext.ext_argparse.LOG = minimal_logger(
                    cement.ext.ext_argparse.LOG.namespace, True)
    except:
        pass
示例#7
0
    def check_recipe(self, recipe=None):
        if recipe is None:
            if not hasattr(self._meta, 'recipe'):
                msg = '{} does not have a recipe!'.format(
                    self.__class__.__name__)
                self.app.log.fatal(msg)
                raise IaaSError(msg)
            recipe = self._meta.recipe
        msg = ''
        for ingredient in recipe:
            if not getattr(self.app.pargs, ingredient['parameter'], None):
                if not is_true(self.setting('batch')) and self.setting(
                        'prompt') and ingredient['ask']:
                    self.app.log.info('Prompt here for {}'.format(
                        ingredient['parameter']))
                    prompt = ArgPrompt()
                    if ingredient.get('options', None):
                        prompt._meta.numbered = True
                        options = ingredient['options']
                        if options.get('values', None):
                            prompt._meta.options = options['values']
                        elif options.get('class', None):
                            columns = getattr(self, '_columns', None)
                            ignored = getattr(self, '_ignored', None)
                            try:
                                if options['module'] not in sys.modules:
                                    try:
                                        __import__(options['module'],
                                                   globals(), locals(), [], 0)
                                    except ImportError as e:
                                        raise IaaSError(
                                            'Unable to import class needed to pull list of options for {} ({})'
                                            .format(ingredient, e.message))
                                klass = getattr(sys.modules[options['module']],
                                                options['class'])
                                instance = klass(
                                    self.app.config.get_section_dict(
                                        options['section']))
                                print('Obtaining a {} of {} ...'.format(
                                    options['method'], options['class']))
                                if options['attribute'].get('filters', None):
                                    filters = getattr(self, '_filters', None)
                                    self._filters = options['attribute'][
                                        'filters']
                                    self.app.log.info('Filter {}.{}.{}'.format(
                                        options['section'], options['class'],
                                        options['method']))
                                    values = getattr(instance,
                                                     options['method'])(
                                                         _filter=self._weigh,
                                                         _collection=instance)
                                    if filters:
                                        self._filters = filters
                                else:
                                    values = getattr(
                                        instance,
                                        options['method'])(detailed=True)

                                if not values.__len__() > 0:
                                    raise FrameworkError(
                                        'There are no {}!'.format(
                                            options['class']))
                                if not isinstance(options['attribute']['show'],
                                                  list):
                                    options['attribute']['show'] = [
                                        options['attribute']['show']
                                    ]
                                self._columns = options['attribute']['show']
                                selection = self._prune(values)
                                i = 0
                                while i < selection.__len__():
                                    for show in options['attribute']['show']:
                                        if not selection[i].get(show, None):
                                            for attr in options['attribute'][
                                                    'alternatives']:
                                                sub = values[i]._evaluate(attr)
                                                if sub:
                                                    selection[i][
                                                        show] = '{}:{}'.format(
                                                            attr, sub)
                                                    break
                                    i += 1

                                prompt._meta.options = [
                                    ','.join(dict(obj).values())
                                    for obj in selection
                                ]
                                self._meta.values = instance
                            except KeyError as e:
                                # raise IaaSError('Ingredient {} options for recipe {}.{} requires an unknown class'.format(ingredient,self.__class__.__name__, self._meta.label))
                                # except ValueError as e:
                                raise IaaSError(
                                    'Ingredient {} for recipe {}.{} requires a "{}" attribute'
                                    .format(ingredient,
                                            self.__class__.__name__,
                                            self._meta.label, e.message))
                            except FrameworkError as e:
                                self.app.log.fatal("'{}': '{}'".format(
                                    e.message, e.msg))
                                print('FATAL error: {}'.format(e.msg))
                                raise e
                            except Exception as e:
                                self.app.log.fatal(e.message)
                                print('FATAL error: {}'.format(e.message))
                                raise e

                            if not columns is None:
                                self._columns = columns
                            if not ignored is None:
                                self._ignored = ignored
                        else:
                            raise IaaSError(
                                'Ingredient {} options for recipe {}.{} are not valid'
                                .format(ingredient, self.__class__.__name__,
                                        self._meta.label))
                        prompt._meta.text = 'Choose {}:'.format(
                            ingredient['description'])
                    else:
                        prompt._meta.numbered = False
                        prompt._meta.options = None
                        prompt._meta.text = 'Enter {}: '.format(
                            ingredient['description'])
                    # prompt._meta.selection_text = 'Enter the {}:'.format(ingredient['parameter'])
                    try:
                        answer = prompt.prompt()
                        if ingredient.get('options', None):
                            options = ingredient['options']
                            if options.get('values', None):
                                setattr(self.app.pargs,
                                        ingredient['parameter'], prompt.input)
                            elif options.get('class', None):
                                index = prompt._meta.options.index(answer)
                                values = [self._meta.values[index]]

                                columns = getattr(self, '_columns', None)
                                ignored = getattr(self, '_ignored', None)
                                self._columns = [options['attribute']['use']]
                                selection = self._prune(values)
                                if not columns is None:
                                    self._columns = columns
                                if not ignored is None:
                                    self._ignored = ignored

                                setattr(
                                    self.app.pargs, ingredient['parameter'],
                                    '{}:{}'.format(
                                        options['attribute']['use'],
                                        selection[0].get(
                                            options['attribute']['use'],
                                            None)))
                                print('{} value will be "{}"'.format(
                                    ingredient['parameter'],
                                    getattr(self.app.pargs,
                                            ingredient['parameter'])))

                                # if string.index(options['attribute']['use'], '/') < 0:
                                #     pass
                                # else:
                                #     setattr(self.app.pargs, ingredient['parameter'], selection[0].get(options['attribute']['use'], None))
                        else:
                            setattr(self.app.pargs, ingredient['parameter'],
                                    prompt.input)
                    except FrameworkError as e:
                        self.app.log.fatal("'{}': '{}'".format(
                            e.message, e.msg))
                        print('FATAL error: {}'.format(e.msg))
                        raise e
                if not getattr(self.app.pargs, ingredient['parameter'], None):
                    msg += "'{}' is required. ({})\n".format(
                        ingredient['parameter'], ingredient['description'])
        if msg.__len__() > 0:
            raise IaaSError(msg)
示例#8
0
def test_is_true():
    # true
    assert misc.is_true(1)
    assert misc.is_true('1')
    assert misc.is_true('true')
    assert misc.is_true('True')
    assert misc.is_true('TRUE')
    assert misc.is_true('tRue')
    assert misc.is_true('yes')
    assert misc.is_true('on')
    assert misc.is_true(True)

    # false
    assert not misc.is_true(0)
    assert not misc.is_true('0')
    assert not misc.is_true('false')
    assert not misc.is_true('False')
    assert not misc.is_true('FALSE')
    assert not misc.is_true('fAlse')
    assert not misc.is_true('no')
    assert not misc.is_true('off')
    assert not misc.is_true(False)
示例#9
0
    def send(self, body, **kw):
        """
        Send an email message via SMTP.  Keyword arguments override
        configuration defaults (cc, bcc, etc).

        :param body: The message body to send
        :type body: multiline string
        :keyword to: List of recipients (generally email addresses)
        :type to: list
        :keyword from_addr: Address (generally email) of the sender
        :type from_addr: string
        :keyword cc: List of CC Recipients
        :type cc: list
        :keyword bcc: List of BCC Recipients
        :type bcc: list
        :keyword subject: Message subject line
        :type subject: string
        :returns: Boolean (``True`` if message is sent successfully, ``False``
         otherwise)

        **Usage**

        .. code-block:: python

            # Using all configuration defaults
            app.mail.send('This is my message body')

            # Overriding configuration defaults
            app.mail.send('My message body'
                from_addr='*****@*****.**',
                to=['*****@*****.**'],
                cc=['*****@*****.**', '*****@*****.**'],
                subject='This is my subject',
                )

        """
        params = self._get_params(**kw)

        if is_true(params['ssl']):
            server = smtplib.SMTP_SSL(params['host'], params['port'],
                                      params['timeout'])
            LOG.debug('%s : initiating ssl' % self._meta.label)
            if is_true(params['tls']):
                LOG.debug('%s : initiating tls' % self._meta.label)
                server.starttls()

        else:
            server = smtplib.SMTP(params['host'], params['port'],
                                  params['timeout'])

        if is_true(params['auth']):
            server.login(params['username'], params['password'])

        if self.app.debug is True:
            server.set_debuglevel(9)

        msg = MIMEMultipart('alternative')
        msg.set_charset('utf-8')

        msg['From'] = params['from_addr']
        msg['To'] = ', '.join(params['to'])
        msg['Cc'] = ', '.join(params['cc'])
        msg['Bcc'] = ', '.join(params['bcc'])
        if params['subject_prefix'] not in [None, '']:
            subject = '%s %s' % (params['subject_prefix'],
                                 params['subject'])
        else:
            subject = params['subject']
        msg['Subject'] = Header(subject)

        part = MIMEText(body)
        msg.attach(part)

        server.send_message(msg)
        server.quit()
示例#10
0
    def send(self, body, **kw):
        """
        Send an email message via SMTP.  Keyword arguments override
        configuration defaults (cc, bcc, etc).

        :param body: The message body to send
        :type body: multiline string
        :keyword to: List of recipients (generally email addresses)
        :type to: list
        :keyword from_addr: Address (generally email) of the sender
        :type from_addr: string
        :keyword cc: List of CC Recipients
        :type cc: list
        :keyword bcc: List of BCC Recipients
        :type bcc: list
        :keyword subject: Message subject line
        :type subject: string
        :returns: Boolean (``True`` if message is sent successfully, ``False``
         otherwise)

        **Usage**

        .. code-block:: python

            # Using all configuration defaults
            app.mail.send('This is my message body')

            # Overriding configuration defaults
            app.mail.send('My message body'
                from_addr='*****@*****.**',
                to=['*****@*****.**'],
                cc=['*****@*****.**', '*****@*****.**'],
                subject='This is my subject',
                )

        """
        params = self._get_params(**kw)

        if is_true(params['ssl']):
            server = smtplib.SMTP_SSL(params['host'], params['port'],
                                      params['timeout'])
            LOG.debug('%s : initiating ssl' % self._meta.label)
            if is_true(params['tls']):
                LOG.debug('%s : initiating tls' % self._meta.label)
                server.starttls()

        else:
            server = smtplib.SMTP(params['host'], params['port'],
                                  params['timeout'])

        if is_true(params['auth']):
            server.login(params['username'], params['password'])

        if self.app.debug is True:
            server.set_debuglevel(9)

        msg = MIMEMultipart('alternative')
        msg.set_charset('utf-8')

        msg['From'] = params['from_addr']
        msg['To'] = ', '.join(params['to'])
        msg['Cc'] = ', '.join(params['cc'])
        msg['Bcc'] = ', '.join(params['bcc'])
        if params['subject_prefix'] not in [None, '']:
            subject = '%s %s' % (params['subject_prefix'], params['subject'])
        else:
            subject = params['subject']
        msg['Subject'] = Header(subject)

        part = MIMEText(body)
        msg.attach(part)

        server.send_message(msg)
        server.quit()