コード例 #1
0
ファイル: test_log.py プロジェクト: yamt/oslo-incubator
 def setUp(self):
     super(LogLevelTestCase, self).setUp()
     self.CONF = self.useFixture(config.Config()).conf
     levels = self.CONF.default_log_levels
     levels.append("nova-test=AUDIT")
     levels.append("nova-not-debug=WARN")
     self.config = self.useFixture(config.Config()).config
     self.config(default_log_levels=levels,
                 verbose=True)
     log.setup('testing')
     self.log = log.getLogger('nova-test')
     self.log_no_debug = log.getLogger('nova-not-debug')
コード例 #2
0
ファイル: wsgi.py プロジェクト: stelford/openstack-common
 def _run(self, application, socket):
     """Start a WSGI server in a new green thread."""
     logger = logging.getLogger('eventlet.wsgi.server')
     eventlet.wsgi.server(socket,
                          application,
                          custom_pool=self.pool,
                          log=logging.WritableLogger(logger))
コード例 #3
0
ファイル: test_log.py プロジェクト: bdelliott/oslo-incubator
 def setUp(self):
     super(LogLevelTestCase, self).setUp()
     levels = CONF.default_log_levels
     levels.append("nova-test=AUDIT")
     self.config(default_log_levels=levels, verbose=True)
     log.setup("testing")
     self.log = log.getLogger("nova-test")
コード例 #4
0
    def setUp(self):
        super(MultiNotifierTestCase, self).setUp()
        self.config = self.useFixture(config.Config()).config
        self.stubs = self.useFixture(moxstubout.MoxStubout()).stubs

        # Mock log to add one to exception_count when log.exception is called

        def mock_exception(cls, *args):
            self.exception_count += 1

        self.exception_count = 0

        notifier_log = log.getLogger('openstack.common.notifier.api')
        self.stubs.Set(notifier_log, "exception", mock_exception)

        # Mock no_op notifier to add one to notify_count when called.
        def mock_notify(cls, *args):
            self.notify_count += 1

        self.notify_count = 0
        self.stubs.Set(no_op_notifier, 'notify', mock_notify)

        # Mock log_notifier to raise RuntimeError when called.

        def mock_notify2(cls, *args):
            raise RuntimeError("Bad notifier.")

        self.stubs.Set(log_notifier, 'notify', mock_notify2)
        self.addCleanup(notifier_api._reset_drivers)
コード例 #5
0
ファイル: wsgi.py プロジェクト: jasondunsmore/oslo-incubator
 def _run(self, application, socket):
     """Start a WSGI server in a new green thread."""
     logger = logging.getLogger('eventlet.wsgi')
     eventlet.wsgi.server(socket,
                          application,
                          custom_pool=self.tg.pool,
                          log=logging.WritableLogger(logger))
コード例 #6
0
    def setUp(self):
        super(MultiNotifierTestCase, self).setUp()
        # Mock log to add one to exception_count when log.exception is called

        def mock_exception(cls, *args):
            self.exception_count += 1

        self.exception_count = 0

        notifier_log = log.getLogger("openstack.common.notifier.api")
        self.stubs.Set(notifier_log, "exception", mock_exception)

        # Mock no_op notifier to add one to notify_count when called.
        def mock_notify(cls, *args):
            self.notify_count += 1

        self.notify_count = 0
        self.stubs.Set(no_op_notifier, "notify", mock_notify)
        # Mock log_notifier to raise RuntimeError when called.

        def mock_notify2(cls, *args):
            raise RuntimeError("Bad notifier.")

        self.stubs.Set(log_notifier, "notify", mock_notify2)
        self.addCleanup(notifier_api._reset_drivers)
コード例 #7
0
    def setUp(self):
        super(MultiNotifierTestCase, self).setUp()

        # Mock log to add one to exception_count when log.exception is called

        def mock_exception(cls, *args):
            self.exception_count += 1

        self.exception_count = 0

        notifier_log = log.getLogger('openstack.common.notifier.api')
        self.stubs.Set(notifier_log, "exception", mock_exception)

        # Mock no_op notifier to add one to notify_count when called.
        def mock_notify(cls, *args):
            self.notify_count += 1

        self.notify_count = 0
        self.stubs.Set(no_op_notifier, 'notify', mock_notify)

        # Mock log_notifier to raise RuntimeError when called.

        def mock_notify2(cls, *args):
            raise RuntimeError("Bad notifier.")

        self.stubs.Set(log_notifier, 'notify', mock_notify2)
        notifier_api._reset_drivers()
コード例 #8
0
    def setUp(self):
        super(NotifierListTestCase, self).setUp()
        list_notifier._reset_drivers()
        # Mock log to add one to exception_count when log.exception is called

        def mock_exception(cls, *args):
            self.exception_count += 1

        self.exception_count = 0
        list_notifier_log = logging.getLogger(
            'openstack.common.notifier.list_notifier')
        self.stubs.Set(list_notifier_log, "exception", mock_exception)
        # Mock no_op notifier to add one to notify_count when called.

        def mock_notify(cls, *args):
            self.notify_count += 1

        self.notify_count = 0
        self.stubs.Set(no_op_notifier, 'notify', mock_notify)
        # Mock log_notifier to raise RuntimeError when called.

        def mock_notify2(cls, *args):
            raise RuntimeError("Bad notifier.")

        self.stubs.Set(log_notifier, 'notify', mock_notify2)
コード例 #9
0
 def setUp(self):
     super(DomainTestCase, self).setUp()
     self.config = self.useFixture(config.Config()).config
     self.config(logging_context_format_string="[%(request_id)s]: " "%(user_identity)s " "%(message)s")
     self.mylog = log.getLogger()
     self._add_handler_with_cleanup(self.mylog)
     self._set_log_level_with_cleanup(self.mylog, logging.DEBUG)
コード例 #10
0
    def setUp(self):
        super(MultiNotifierTestCase, self).setUp()
        self.config = self.useFixture(config.Config()).config
        self.stubs = self.useFixture(moxstubout.MoxStubout()).stubs
        # Mock log to add one to exception_count when log.exception is called

        def mock_exception(cls, *args):
            self.exception_count += 1

        self.exception_count = 0

        notifier_log = log.getLogger(
            'openstack.common.notifier.api')
        self.stubs.Set(notifier_log, "exception", mock_exception)

        # Mock no_op notifier to add one to notify_count when called.
        def mock_notify(cls, *args):
            self.notify_count += 1

        self.notify_count = 0
        self.stubs.Set(no_op_notifier, 'notify', mock_notify)
        # Mock log_notifier to raise RuntimeError when called.

        def mock_notify2(cls, *args):
            raise RuntimeError("Bad notifier.")

        self.stubs.Set(log_notifier, 'notify', mock_notify2)
        self.addCleanup(notifier_api._reset_drivers)
コード例 #11
0
ファイル: test_log.py プロジェクト: 4383/oslo-incubator
 def setUp(self):
     super(LogLevelTestCase, self).setUp()
     levels = CONF.default_log_levels
     levels.append("nova-test=AUDIT")
     self.config(default_log_levels=levels,
                 verbose=True)
     log.setup('testing')
     self.log = log.getLogger('nova-test')
コード例 #12
0
 def setUp(self):
     super(SetSQLModeTestCase, self).setUp()
     self.dbapi_mock = mock.Mock()
     self.cursor = mock.Mock()
     self.dbapi_mock.cursor.return_value = self.cursor
     # Add fake logger so we can verify log messages
     self.logger = log.getLogger('openstack.common.db.sqlalchemy.session')
     self._add_handler_with_cleanup(self.logger)
コード例 #13
0
ファイル: test_log.py プロジェクト: 4383/oslo-incubator
 def setUp(self):
     super(JSONFormatterTestCase, self).setUp()
     self.log = log.getLogger('test-json')
     self.stream = cStringIO.StringIO()
     handler = logging.StreamHandler(self.stream)
     handler.setFormatter(log.JSONFormatter())
     self.log.logger.addHandler(handler)
     self.log.logger.setLevel(logging.DEBUG)
コード例 #14
0
ファイル: test_log.py プロジェクト: mtreinish/oslo-incubator
 def setUp(self):
     super(JSONFormatterTestCase, self).setUp()
     self.log = log.getLogger('test-json')
     self.stream = cStringIO.StringIO()
     handler = logging.StreamHandler(self.stream)
     handler.setFormatter(log.JSONFormatter())
     self.log.logger.addHandler(handler)
     self.log.logger.setLevel(logging.DEBUG)
コード例 #15
0
    def _call_set_callback(self, listen_mock, sql_mode=None, realmode=None):
        engine = self.FakeEngine(realmode=realmode)

        logger = log.getLogger('openstack.common.db.sqlalchemy.session')
        self._set_log_level_with_cleanup(logger, logging.DEBUG)
        self._add_handler_with_cleanup(logger)

        session._mysql_set_mode_callback(engine, sql_mode=sql_mode)
        return engine
コード例 #16
0
ファイル: test_log.py プロジェクト: thomasem/oslo-incubator
 def setUp(self):
     super(LogLevelTestCase, self).setUp()
     self.CONF = self.useFixture(config.Config()).conf
     levels = self.CONF.default_log_levels
     levels.append("nova-test=AUDIT")
     self.config = self.useFixture(config.Config()).config
     self.config(default_log_levels=levels, verbose=True)
     log.setup('testing')
     self.log = log.getLogger('nova-test')
コード例 #17
0
def notify(_context, message):
    """Notifies the recipient of the desired event given the model.
    Log notifications using openstack's default logging system"""

    priority = message.get('priority', CONF.default_notification_level)
    priority = priority.lower()
    logger = logging.getLogger('openstack.common.notification.%s' %
                               message['event_type'])
    getattr(logger, priority)(jsonutils.dumps(message))
コード例 #18
0
ファイル: test_log.py プロジェクト: mtreinish/oslo-incubator
    def setUp(self):
        super(LoggerTestCase, self).setUp()

        # common context has different fields to the defaults in log.py
        self.config(logging_context_format_string='%(asctime)s %(levelname)s '
                                                  '%(name)s [%(request_id)s '
                                                  '%(user)s %(tenant)s] '
                                                  '%(message)s')

        self.log = log.getLogger()
コード例 #19
0
ファイル: test_log.py プロジェクト: managedit/oslo-incubator
    def setUp(self):
        super(LoggerTestCase, self).setUp()

        # common context has different fields to the defaults in log.py
        self.config(logging_context_format_string='%(asctime)s %(levelname)s '
                                                  '%(name)s [%(request_id)s '
                                                  '%(user)s %(tenant)s] '
                                                  '%(message)s')

        self.log = log.getLogger()
コード例 #20
0
def notify(_context, message):
    """Notifies the recipient of the desired event given the model.
    Log notifications using openstack's default logging system"""

    priority = message.get('priority',
                           CONF.default_notification_level)
    priority = priority.lower()
    logger = logging.getLogger(
            'openstack.common.notification.%s' % message['event_type'])
    getattr(logger, priority)(json.dumps(message))
コード例 #21
0
ファイル: ec2.py プロジェクト: SpamapS/os-collect-config
 def _fetch_metadata(self, fetch_url):
     try:
         r = self.session.get(fetch_url)
         r.raise_for_status()
     except self._requests_impl.exceptions.RequestException as e:
         log.getLogger(__name__).warn(e)
         raise exc.Ec2MetadataNotAvailable
     content = r.text
     if fetch_url[-1] == '/':
         new_content = {}
         for subkey in content.split("\n"):
             if '=' in subkey:
                 subkey = subkey[:subkey.index('=')] + '/'
             sub_fetch_url = fetch_url + subkey
             if subkey[-1] == '/':
                 subkey = subkey[:-1]
             new_content[subkey] = self._fetch_metadata(sub_fetch_url)
         content = new_content
     return content
コード例 #22
0
 def setUp(self):
     super(ContextFormatterTestCase, self).setUp()
     self.config = self.useFixture(config.Config()).config
     self.config(logging_context_format_string="HAS CONTEXT "
                                               "[%(request_id)s]: "
                                               "%(message)s",
                 logging_default_format_string="NOCTXT: %(message)s",
                 logging_debug_format_suffix="--DBG")
     self.log = log.getLogger('')  # obtain root logger instead of 'unknown'
     self._add_handler_with_cleanup(self.log)
     self._set_log_level_with_cleanup(self.log, logging.DEBUG)
コード例 #23
0
ファイル: test_log.py プロジェクト: neutronlib/oslo-incubator
 def setUp(self):
     super(DomainTestCase, self).setUp()
     self.config = self.useFixture(config.Config()).config
     self.config(logging_context_format_string="[%(request_id)s]: "
                                               "%(user_identity)s "
                                               "%(message)s")
     self.mylog = log.getLogger()
     self.stream = six.StringIO()
     handler = logging.StreamHandler(self.stream)
     handler.setFormatter(log.ContextFormatter())
     self.mylog.logger.addHandler(handler)
     self.mylog.logger.setLevel(logging.DEBUG)
コード例 #24
0
 def setUp(self):
     super(FancyRecordTestCase, self).setUp()
     self.config = self.useFixture(config.Config()).config
     # NOTE(sdague): use the different formatters to demonstrate format
     # string with valid fancy keys and without. Slightly hacky, but given
     # the way log objects layer up seemed to be most concise approach
     self.config(
         logging_context_format_string="%(color)s " "[%(request_id)s]: " "%(instance)s" "%(message)s",
         logging_default_format_string="%(missing)s: %(message)s",
     )
     self.colorlog = log.getLogger()
     self._add_handler_with_cleanup(self.colorlog, log.ColorHandler)
     self._set_log_level_with_cleanup(self.colorlog, logging.DEBUG)
コード例 #25
0
    def test_excepthook_logs_exception(self):
        product_name = "somename"
        exc_log = log.getLogger(product_name)

        self._add_handler_with_cleanup(exc_log)
        excepthook = log._create_logging_excepthook(product_name)

        try:
            raise Exception("Some error happened")
        except Exception:
            excepthook(*sys.exc_info())

        expected_string = "CRITICAL somename [-] " "Exception: Some error happened"
        self.assertTrue(expected_string in self.stream.getvalue(), msg="Exception is not logged")
コード例 #26
0
ファイル: test_log.py プロジェクト: mtreinish/oslo-incubator
 def setUp(self):
     super(LegacyFormatterTestCase, self).setUp()
     self.config(logging_context_format_string="HAS CONTEXT "
                                               "[%(request_id)s]: "
                                               "%(message)s",
                 logging_default_format_string="NOCTXT: %(message)s",
                 logging_debug_format_suffix="--DBG")
     self.log = log.getLogger()
     self.stream = cStringIO.StringIO()
     self.handler = logging.StreamHandler(self.stream)
     self.handler.setFormatter(log.LegacyFormatter())
     self.log.logger.addHandler(self.handler)
     self.level = self.log.logger.getEffectiveLevel()
     self.log.logger.setLevel(logging.DEBUG)
コード例 #27
0
ファイル: test_log.py プロジェクト: stelford/openstack-common
 def setUp(self):
     super(LegacyFormatterTestCase, self).setUp()
     self.config(logging_context_format_string="HAS CONTEXT "
                                               "[%(request_id)s]: "
                                               "%(message)s",
                 logging_default_format_string="NOCTXT: %(message)s",
                 logging_debug_format_suffix="--DBG")
     self.log = log.getLogger()
     self.stream = cStringIO.StringIO()
     self.handler = logging.StreamHandler(self.stream)
     self.handler.setFormatter(log.LegacyFormatter())
     self.log.logger.addHandler(self.handler)
     self.level = self.log.logger.getEffectiveLevel()
     self.log.logger.setLevel(logging.DEBUG)
コード例 #28
0
ファイル: test_log.py プロジェクト: thomasem/oslo-incubator
 def setUp(self):
     super(ContextFormatterTestCase, self).setUp()
     self.config = self.useFixture(config.Config()).config
     self.config(logging_context_format_string="HAS CONTEXT "
                 "[%(request_id)s]: "
                 "%(message)s",
                 logging_default_format_string="NOCTXT: %(message)s",
                 logging_debug_format_suffix="--DBG")
     self.log = log.getLogger()
     self.stream = six.StringIO()
     self.handler = logging.StreamHandler(self.stream)
     self.handler.setFormatter(log.ContextFormatter())
     self.log.logger.addHandler(self.handler)
     self.addCleanup(self.log.logger.removeHandler, self.handler)
     self.level = self.log.logger.getEffectiveLevel()
     self.log.logger.setLevel(logging.DEBUG)
     self.addCleanup(self.log.logger.setLevel, self.level)
コード例 #29
0
    def test_error_notification(self):
        self.stubs.Set(cfg.CONF, "notification_driver", ["openstack.common.notifier.rabbit_notifier"])
        self.stubs.Set(cfg.CONF, "publish_errors", True)
        LOG = log.getLogger("common")
        log.setup(None)
        msgs = []

        def mock_notify(context, topic, data):
            msgs.append(data)

        self.stubs.Set(rpc, "notify", mock_notify)
        LOG.error("foo")
        self.assertEqual(1, len(msgs))
        msg = msgs[0]
        self.assertEqual(msg["event_type"], "error_notification")
        self.assertEqual(msg["priority"], "ERROR")
        self.assertEqual(msg["payload"]["error"], "foo")
コード例 #30
0
ファイル: test_log.py プロジェクト: rsokolkov/oslo-incubator
 def setUp(self):
     super(ContextFormatterTestCase, self).setUp()
     self.config = self.useFixture(config.Config()).config
     self.config(logging_context_format_string="HAS CONTEXT "
                                               "[%(request_id)s]: "
                                               "%(message)s",
                 logging_default_format_string="NOCTXT: %(message)s",
                 logging_debug_format_suffix="--DBG")
     self.log = log.getLogger()
     self.stream = six.StringIO()
     self.handler = logging.StreamHandler(self.stream)
     self.handler.setFormatter(log.ContextFormatter())
     self.log.logger.addHandler(self.handler)
     self.addCleanup(self.log.logger.removeHandler, self.handler)
     self.level = self.log.logger.getEffectiveLevel()
     self.log.logger.setLevel(logging.DEBUG)
     self.addCleanup(self.log.logger.setLevel, self.level)
コード例 #31
0
ファイル: wsgi.py プロジェクト: fajoy/openstack-hello
    def __init__(self, name, app, host='0.0.0.0', port=0, pool_size=None,
                       protocol=eventlet.wsgi.HttpProtocol, backlog=128,
                       use_ssl=False, max_url_len=None):
        """Initialize, but do not start, a WSGI server.

        :param name: Pretty name for logging.
        :param app: The WSGI application to serve.
        :param host: IP address to serve the application.
        :param port: Port number to server the application.
        :param pool_size: Maximum number of eventlets to spawn concurrently.
        :param backlog: Maximum number of queued connections.
        :param max_url_len: Maximum length of permitted URLs.
        :returns: None
        :raises: nova.exception.InvalidInput
        """
        self.name = name
        self.app = app
        self._server = None
        self._protocol = protocol
        self._pool = eventlet.GreenPool(pool_size or self.default_pool_size)
        self._logger = logging.getLogger("%s.wsgi.server" % self.name)
        self._wsgi_logger = logging.WritableLogger(self._logger)
        self._use_ssl = use_ssl
        self._max_url_len = max_url_len

        if backlog < 1:
            raise exception.InvalidInput(
                    reason='The backlog must be more than 1')

        bind_addr = (host, port)
        # TODO(dims): eventlet's green dns/socket module does not actually
        # support IPv6 in getaddrinfo(). We need to get around this in the
        # future or monitor upstream for a fix
        try:
            info = socket.getaddrinfo(bind_addr[0],
                                      bind_addr[1],
                                      socket.AF_UNSPEC,
                                      socket.SOCK_STREAM)[0]
            family = info[0]
            bind_addr = info[-1]
        except Exception:
            family = socket.AF_INET

        self._socket = eventlet.listen(bind_addr, family, backlog=backlog)
        (self.host, self.port) = self._socket.getsockname()[0:2]
        LOG.info(_("%(name)s listening on %(host)s:%(port)s") % self.__dict__)
コード例 #32
0
    def test_error_notification(self):
        self.stubs.Set(cfg.CONF, 'notification_driver',
                       ['openstack.common.notifier.rabbit_notifier'])
        self.stubs.Set(cfg.CONF, 'publish_errors', True)
        LOG = log.getLogger('common')
        log.setup(None)
        msgs = []

        def mock_notify(context, topic, data):
            msgs.append(data)

        self.stubs.Set(rpc, 'notify', mock_notify)
        LOG.error('foo')
        self.assertEqual(1, len(msgs))
        msg = msgs[0]
        self.assertEqual(msg['event_type'], 'error_notification')
        self.assertEqual(msg['priority'], 'ERROR')
        self.assertEqual(msg['payload']['error'], 'foo')
コード例 #33
0
    def test_error_notification(self):
        self.stubs.Set(cfg.CONF, 'notification_driver',
                       ['openstack.common.notifier.rabbit_notifier'])
        self.stubs.Set(cfg.CONF, 'publish_errors', True)
        LOG = log.getLogger('common')
        log.setup(None)
        msgs = []

        def mock_notify(context, topic, data):
            msgs.append(data)

        self.stubs.Set(rpc, 'notify', mock_notify)
        LOG.error('foo')
        self.assertEqual(1, len(msgs))
        msg = msgs[0]
        self.assertEqual(msg['event_type'], 'error_notification')
        self.assertEqual(msg['priority'], 'ERROR')
        self.assertEqual(msg['payload']['error'], 'foo')
コード例 #34
0
    def test_error_notification(self):
        self.config(publish_errors=True, use_stderr=False)

        def mock_notify(context, message):
            msgs.append(message)

        msgs = []
        self.stubs.Set(no_op_notifier, 'notify', mock_notify)

        LOG = log.getLogger('test_error_notification.common')
        log.setup('test_error_notification')

        LOG.error('foo')
        self.assertEqual(1, len(msgs))
        msg = msgs[0]
        self.assertEqual(msg['event_type'], 'error_notification')
        self.assertEqual(msg['priority'], 'ERROR')
        self.assertEqual(msg['payload']['error'], 'foo')
コード例 #35
0
ファイル: test_log.py プロジェクト: bdelliott/oslo-incubator
    def test_excepthook_logs_exception(self):
        product_name = "somename"
        exc_log = log.getLogger(product_name)

        stream = cStringIO.StringIO()
        handler = logging.StreamHandler(stream)
        handler.setFormatter(log.ContextFormatter())
        exc_log.logger.addHandler(handler)
        self.addCleanup(exc_log.logger.removeHandler, handler)
        excepthook = log._create_logging_excepthook(product_name)

        try:
            raise Exception("Some error happened")
        except Exception:
            excepthook(*sys.exc_info())

        expected_string = "CRITICAL somename [-] Some error happened"
        self.assertTrue(expected_string in stream.getvalue(), msg="Exception is not logged")
コード例 #36
0
    def test_error_notification(self):
        self.config(publish_errors=True, use_stderr=False)

        def mock_notify(context, message):
            msgs.append(message)

        msgs = []
        self.stubs.Set(no_op_notifier, "notify", mock_notify)

        LOG = log.getLogger("test_error_notification.common")
        log.setup("test_error_notification")

        LOG.error("foo")
        self.assertEqual(1, len(msgs))
        msg = msgs[0]
        self.assertEqual(msg["event_type"], "error_notification")
        self.assertEqual(msg["priority"], "ERROR")
        self.assertEqual(msg["payload"]["error"], "foo")
コード例 #37
0
ファイル: test_log.py プロジェクト: mtreinish/oslo-incubator
    def setUp(self):
        super(FancyRecordTestCase, self).setUp()
        # NOTE(sdague): use the different formatters to demonstrate format
        # string with valid fancy keys and without. Slightly hacky, but given
        # the way log objects layer up seemed to be most concise approach
        self.config(logging_context_format_string="%(color)s "
                                                  "[%(request_id)s]: "
                                                  "%(message)s",
                    logging_default_format_string="%(missing)s: %(message)s")
        self.stream = cStringIO.StringIO()

        self.colorhandler = log.ColorHandler(self.stream)
        self.colorhandler.setFormatter(log.LegacyFormatter())

        self.colorlog = log.getLogger()
        self.colorlog.logger.addHandler(self.colorhandler)
        self.level = self.colorlog.logger.getEffectiveLevel()
        self.colorlog.logger.setLevel(logging.DEBUG)
コード例 #38
0
ファイル: test_log.py プロジェクト: 4383/oslo-incubator
    def setUp(self):
        super(FancyRecordTestCase, self).setUp()
        # NOTE(sdague): use the different formatters to demonstrate format
        # string with valid fancy keys and without. Slightly hacky, but given
        # the way log objects layer up seemed to be most concise approach
        self.config(logging_context_format_string="%(color)s "
                                                  "[%(request_id)s]: "
                                                  "%(message)s",
                    logging_default_format_string="%(missing)s: %(message)s")
        self.stream = cStringIO.StringIO()

        self.colorhandler = log.ColorHandler(self.stream)
        self.colorhandler.setFormatter(log.ContextFormatter())

        self.colorlog = log.getLogger()
        self.colorlog.logger.addHandler(self.colorhandler)
        self.level = self.colorlog.logger.getEffectiveLevel()
        self.colorlog.logger.setLevel(logging.DEBUG)
コード例 #39
0
    def test_error_notification(self):
        self.config(publish_errors=True,
                    use_stderr=False)

        def mock_notify(context, message):
            msgs.append(message)

        msgs = []
        self.stubs.Set(no_op_notifier, 'notify', mock_notify)

        LOG = log.getLogger('test_error_notification.common')
        log.setup('test_error_notification')

        LOG.error('foo')
        self.assertEqual(1, len(msgs))
        msg = msgs[0]
        self.assertEqual(msg['event_type'], 'error_notification')
        self.assertEqual(msg['priority'], 'ERROR')
        self.assertEqual(msg['payload']['error'], 'foo')
コード例 #40
0
ファイル: test_log.py プロジェクト: 4383/oslo-incubator
    def test_excepthook_logs_exception(self):
        product_name = 'somename'
        exc_log = log.getLogger(product_name)

        stream = cStringIO.StringIO()
        handler = logging.StreamHandler(stream)
        handler.setFormatter(log.ContextFormatter())
        exc_log.logger.addHandler(handler)
        self.addCleanup(exc_log.logger.removeHandler, handler)
        excepthook = log._create_logging_excepthook(product_name)

        try:
            raise Exception('Some error happened')
        except Exception:
            excepthook(*sys.exc_info())

        expected_string = "CRITICAL somename [-] Some error happened"
        self.assertTrue(expected_string in stream.getvalue(),
                        msg="Exception is not logged")
コード例 #41
0
# -*- coding: utf-8 -*-
''' Interface for database access '''

from oslo.config import cfg
from openstack.common.db import api as db_api
from openstack.common import log as logging

# from forest import utils

CONF = cfg.CONF

_BACKEND_MAPPING = {'sqlalchemy': 'forest.db.sqlalchemy.api'}

IMPL = db_api.DBAPI(backend_mapping=_BACKEND_MAPPING)
LOG = logging.getLogger(__name__)


def get_session(context=None):
    ''' Get session from context '''
    return IMPL.get_session(context)


def job_flow_get(context, job_flow_id):
    return IMPL.job_flow_get(context, job_flow_id)


def job_flow_get_all(context, tenant_only=True):
    return IMPL.job_flow_get_all(context, tenant_only)


def job_flow_get_all_by_tenant(context):
コード例 #42
0
ファイル: test_log.py プロジェクト: 4383/oslo-incubator
 def test_child_log_has_level_of_parent_flag(self):
     l = log.getLogger('nova-test.foo')
     self.assertEqual(logging.AUDIT, l.logger.getEffectiveLevel())
コード例 #43
0
 def setUp(self):
     super(JSONFormatterTestCase, self).setUp()
     self.log = log.getLogger('test-json')
     self._add_handler_with_cleanup(self.log, formatter=log.JSONFormatter)
     self._set_log_level_with_cleanup(self.log, logging.DEBUG)
コード例 #44
0
ファイル: collect.py プロジェクト: SpamapS/os-collect-config
from os_collect_config import ec2
from os_collect_config import exc
from os_collect_config import heat_local
from oslo.config import cfg

opts = [
    cfg.StrOpt('command',
               short='c',
               help='Command to run on metadata changes.'),
    cfg.StrOpt('cachedir',
               default='/var/run/os-collect-config',
               help='Directory in which to store local cache of metadata'),
]

CONF = cfg.CONF
logger = log.getLogger('os-collect-config')

COLLECTORS = (ec2, cfn, heat_local)


def setup_conf():
    ec2_group = cfg.OptGroup(name='ec2',
                             title='EC2 Metadata options')

    cfn_group = cfg.OptGroup(name='cfn',
                             title='CloudFormation API Metadata options')

    heat_local_group = cfg.OptGroup(name='heat_local',
                                    title='Heat Local Metadata options')

    CONF.register_group(ec2_group)
コード例 #45
0
ファイル: test_log.py プロジェクト: mtreinish/oslo-incubator
 def test_child_log_has_level_of_parent_flag(self):
     l = log.getLogger('nova-test.foo')
     self.assertEqual(logging.AUDIT, l.logger.getEffectiveLevel())
コード例 #46
0
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

import mock

from openstack.common.db.sqlalchemy import test_migrations as migrate
from openstack.common import log as logging
from openstack.common import test


LOG = logging.getLogger(__name__)


class TestWalkVersions(test.BaseTestCase, migrate.WalkVersionsMixin):
    def setUp(self):
        super(TestWalkVersions, self).setUp()
        self.migration_api = mock.MagicMock()
        self.engine = mock.MagicMock()
        self.REPOSITORY = mock.MagicMock()
        self.INIT_VERSION = 4

    def test_migrate_up(self):
        self.migration_api.db_version.return_value = 141

        self._migrate_up(self.engine, 141)
コード例 #47
0
ファイル: test_log.py プロジェクト: 4383/oslo-incubator
 def setUp(self):
     super(LoggerTestCase, self).setUp()
     self.log = log.getLogger()