Python logging.raiseExceptions() Examples

The following are 30 code examples for showing how to use logging.raiseExceptions(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module logging , or try the search function .

Example 1
Project: ironpython3   Author: IronLanguages   File: test_logging.py    License: Apache License 2.0 6 votes vote down vote up
def test_error_handling(self):
        h = TestStreamHandler(BadStream())
        r = logging.makeLogRecord({})
        old_raise = logging.raiseExceptions
        old_stderr = sys.stderr
        try:
            h.handle(r)
            self.assertIs(h.error_record, r)
            h = logging.StreamHandler(BadStream())
            sys.stderr = sio = io.StringIO()
            h.handle(r)
            self.assertIn('\nRuntimeError: deliberate mistake\n',
                          sio.getvalue())
            logging.raiseExceptions = False
            sys.stderr = sio = io.StringIO()
            h.handle(r)
            self.assertEqual('', sio.getvalue())
        finally:
            logging.raiseExceptions = old_raise
            sys.stderr = old_stderr

# -- The following section could be moved into a server_helper.py module
# -- if it proves to be of wider utility than just test_logging 
Example 2
Project: kll   Author: kiibohd   File: parser.py    License: GNU General Public License v3.0 6 votes vote down vote up
def Parser_debug(enable, stream=None):
    '''
    Enables/Disables debug logger for parser.py

    NOTE: This is not really multi-thread friendly

    @param stream: StringIO stream to use
    @param enable: Enable/disable debug stream
    '''
    global debug
    debug = enable

    if enable:
        logging.raiseExceptions = False
        log.setLevel(logging.DEBUG)
        ch = logging.StreamHandler(stream)
        log.addHandler(ch) 
Example 3
def test_error_handling(self):
        h = TestStreamHandler(BadStream())
        r = logging.makeLogRecord({})
        old_raise = logging.raiseExceptions

        try:
            h.handle(r)
            self.assertIs(h.error_record, r)

            h = logging.StreamHandler(BadStream())
            with support.captured_stderr() as stderr:
                h.handle(r)
                msg = '\nRuntimeError: deliberate mistake\n'
                self.assertIn(msg, stderr.getvalue())

            logging.raiseExceptions = False
            with support.captured_stderr() as stderr:
                h.handle(r)
                self.assertEqual('', stderr.getvalue())
        finally:
            logging.raiseExceptions = old_raise

# -- The following section could be moved into a server_helper.py module
# -- if it proves to be of wider utility than just test_logging 
Example 4
Project: Emoji-Tools   Author: MitchTalmadge   File: py23.py    License: GNU General Public License v3.0 6 votes vote down vote up
def callHandlers(self, record):
		# this is the same as Python 3.5's logging.Logger.callHandlers
		c = self
		found = 0
		while c:
			for hdlr in c.handlers:
				found = found + 1
				if record.levelno >= hdlr.level:
					hdlr.handle(record)
			if not c.propagate:
				c = None  # break out
			else:
				c = c.parent
		if (found == 0):
			if logging.lastResort:
				if record.levelno >= logging.lastResort.level:
					logging.lastResort.handle(record)
			elif logging.raiseExceptions and not self.manager.emittedNoHandlerWarning:
				sys.stderr.write("No handlers could be found for logger"
								 " \"%s\"\n" % self.name)
				self.manager.emittedNoHandlerWarning = True 
Example 5
Project: koku   Author: project-koku   File: test_aws_org_unit_crawler.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_unknown_exception(self, mock_session):
        """Test botocore general ClientError."""
        logging.disable(logging.NOTSET)
        mock_session.client = MagicMock()
        unit_crawler = AWSOrgUnitCrawler(self.account)
        unit_crawler._init_session()
        unit_crawler._client.list_roots.side_effect = Exception("unknown error")
        with self.assertLogs(logger=crawler_log, level=logging.raiseExceptions):
            unit_crawler.crawl_account_hierarchy() 
Example 6
Project: pytest   Author: pytest-dev   File: logging.py    License: MIT License 5 votes vote down vote up
def handleError(self, record: logging.LogRecord) -> None:
        if logging.raiseExceptions:
            # Fail the test if the log message is bad (emit failed).
            # The default behavior of logging is to print "Logging error"
            # to stderr with the call stack and some extra details.
            # pytest wants to make such mistakes visible during testing.
            raise 
Example 7
Project: Fluid-Designer   Author: Microvellum   File: test_logging.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_error_handling(self):
        h = TestStreamHandler(BadStream())
        r = logging.makeLogRecord({})
        old_raise = logging.raiseExceptions

        try:
            h.handle(r)
            self.assertIs(h.error_record, r)

            h = logging.StreamHandler(BadStream())
            with support.captured_stderr() as stderr:
                h.handle(r)
                msg = '\nRuntimeError: deliberate mistake\n'
                self.assertIn(msg, stderr.getvalue())

            logging.raiseExceptions = False
            with support.captured_stderr() as stderr:
                h.handle(r)
                self.assertEqual('', stderr.getvalue())
        finally:
            logging.raiseExceptions = old_raise

# -- The following section could be moved into a server_helper.py module
# -- if it proves to be of wider utility than just test_logging 
Example 8
Project: Fluid-Designer   Author: Microvellum   File: test_logging.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_last_resort(self):
        # Test the last resort handler
        root = self.root_logger
        root.removeHandler(self.root_hdlr)
        old_lastresort = logging.lastResort
        old_raise_exceptions = logging.raiseExceptions

        try:
            with support.captured_stderr() as stderr:
                root.debug('This should not appear')
                self.assertEqual(stderr.getvalue(), '')
                root.warning('Final chance!')
                self.assertEqual(stderr.getvalue(), 'Final chance!\n')

            # No handlers and no last resort, so 'No handlers' message
            logging.lastResort = None
            with support.captured_stderr() as stderr:
                root.warning('Final chance!')
                msg = 'No handlers could be found for logger "root"\n'
                self.assertEqual(stderr.getvalue(), msg)

            # 'No handlers' message only printed once
            with support.captured_stderr() as stderr:
                root.warning('Final chance!')
                self.assertEqual(stderr.getvalue(), '')

            # If raiseExceptions is False, no message is printed
            root.manager.emittedNoHandlerWarning = False
            logging.raiseExceptions = False
            with support.captured_stderr() as stderr:
                root.warning('Final chance!')
                self.assertEqual(stderr.getvalue(), '')
        finally:
            root.addHandler(self.root_hdlr)
            logging.lastResort = old_lastresort
            logging.raiseExceptions = old_raise_exceptions 
Example 9
Project: Fluid-Designer   Author: Microvellum   File: test_logging.py    License: GNU General Public License v3.0 5 votes vote down vote up
def setUp(self):
        super(ShutdownTest, self).setUp()
        self.called = []

        raise_exceptions = logging.raiseExceptions
        self.addCleanup(setattr, logging, 'raiseExceptions', raise_exceptions) 
Example 10
Project: Fluid-Designer   Author: Microvellum   File: test_logging.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_with_other_error_in_acquire_without_raise(self):
        logging.raiseExceptions = False
        self._test_with_failure_in_method('acquire', IndexError) 
Example 11
Project: Fluid-Designer   Author: Microvellum   File: test_logging.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_with_other_error_in_flush_without_raise(self):
        logging.raiseExceptions = False
        self._test_with_failure_in_method('flush', IndexError) 
Example 12
Project: Fluid-Designer   Author: Microvellum   File: test_logging.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_with_other_error_in_acquire_with_raise(self):
        logging.raiseExceptions = True
        self.assertRaises(IndexError, self._test_with_failure_in_method,
                          'acquire', IndexError) 
Example 13
Project: Fluid-Designer   Author: Microvellum   File: test_logging.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_with_other_error_in_flush_with_raise(self):
        logging.raiseExceptions = True
        self.assertRaises(IndexError, self._test_with_failure_in_method,
                          'flush', IndexError) 
Example 14
Project: Fluid-Designer   Author: Microvellum   File: test_logging.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_with_other_error_in_close_with_raise(self):
        logging.raiseExceptions = True
        self.assertRaises(IndexError, self._test_with_failure_in_method,
                          'close', IndexError) 
Example 15
Project: Fluid-Designer   Author: Microvellum   File: test_logging.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_log_invalid_level_with_raise(self):
        with support.swap_attr(logging, 'raiseExceptions', True):
            self.assertRaises(TypeError, self.logger.log, '10', 'test message') 
Example 16
Project: Fluid-Designer   Author: Microvellum   File: test_logging.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_log_invalid_level_no_raise(self):
        with support.swap_attr(logging, 'raiseExceptions', False):
            self.logger.log('10', 'test message')  # no exception happens 
Example 17
Project: notifiers   Author: liiight   File: logging.py    License: MIT License 5 votes vote down vote up
def handleError(self, record):
        """
        Handles any errors raised during the :meth:`emit` method. Will only try to pass exceptions to fallback notifier
        (if defined) in case the exception is a sub-class of :exc:`~notifiers.exceptions.NotifierException`

        :param record: :class:`logging.LogRecord`
        """
        if logging.raiseExceptions:
            t, v, tb = sys.exc_info()
            if issubclass(t, NotifierException) and self.fallback:
                msg = f"Could not log msg to provider '{self.provider.name}'!\n{v}"
                self.fallback_defaults["message"] = msg
                self.fallback.notify(**self.fallback_defaults)
            else:
                super().handleError(record) 
Example 18
Project: txaio   Author: crossbario   File: aio.py    License: MIT License 5 votes vote down vote up
def start_logging(out=_stdout, level='info'):
    """
    Begin logging.

    :param out: if provided, a file-like object to log to. By default, this is
                stdout.
    :param level: the maximum log-level to emit (a string)
    """
    global _log_level, _loggers, _started_logging
    if level not in log_levels:
        raise RuntimeError(
            "Invalid log level '{0}'; valid are: {1}".format(
                level, ', '.join(log_levels)
            )
        )

    if _started_logging:
        return

    _started_logging = True
    _log_level = level

    handler = _TxaioFileHandler(out)
    logging.getLogger().addHandler(handler)
    # note: Don't need to call basicConfig() or similar, because we've
    # now added at least one handler to the root logger
    logging.raiseExceptions = True  # FIXME
    level_to_stdlib = {
        'critical': logging.CRITICAL,
        'error': logging.ERROR,
        'warn': logging.WARNING,
        'info': logging.INFO,
        'debug': logging.DEBUG,
        'trace': logging.DEBUG,
    }
    logging.getLogger().setLevel(level_to_stdlib[level])
    # make sure any loggers we created before now have their log-level
    # set (any created after now will get it from _log_level
    for logger in _loggers:
        logger._set_log_level(level) 
Example 19
Project: content   Author: demisto   File: EWSMailSender.py    License: MIT License 5 votes vote down vote up
def start_logging():
    logging.raiseExceptions = False
    global log_stream
    global log_handler
    if log_stream is None:
        log_stream = StringIO()
        log_handler = logging.StreamHandler(stream=log_stream)
        log_handler.setFormatter(logging.Formatter(logging.BASIC_FORMAT))
        logger = logging.getLogger()
        logger.addHandler(log_handler)
        logger.setLevel(logging.DEBUG) 
Example 20
Project: content   Author: demisto   File: EWSv2.py    License: MIT License 5 votes vote down vote up
def start_logging():
    global log_stream
    global log_handler
    logging.raiseExceptions = False
    if log_stream is None:
        log_stream = StringIO()
        log_handler = logging.StreamHandler(stream=log_stream)
        log_handler.setFormatter(logging.Formatter(logging.BASIC_FORMAT))
        logger = logging.getLogger()
        logger.addHandler(log_handler)
        logger.setLevel(logging.DEBUG)


# Exchange 2010 Fixes 
Example 21
Project: content   Author: demisto   File: EWSO365.py    License: MIT License 5 votes vote down vote up
def start_logging():
    global log_stream
    global log_handler
    logging.raiseExceptions = False
    if log_stream is None:
        log_stream = StringIO()
        log_handler = logging.StreamHandler(stream=log_stream)
        log_handler.setFormatter(logging.Formatter(logging.BASIC_FORMAT))
        logger = logging.getLogger()
        logger.addHandler(log_handler)
        logger.setLevel(logging.DEBUG) 
Example 22
Project: ironpython3   Author: IronLanguages   File: test_logging.py    License: Apache License 2.0 5 votes vote down vote up
def test_last_resort(self):
        # Test the last resort handler
        root = self.root_logger
        root.removeHandler(self.root_hdlr)
        old_stderr = sys.stderr
        old_lastresort = logging.lastResort
        old_raise_exceptions = logging.raiseExceptions
        try:
            sys.stderr = sio = io.StringIO()
            root.debug('This should not appear')
            self.assertEqual(sio.getvalue(), '')
            root.warning('This is your final chance!')
            self.assertEqual(sio.getvalue(), 'This is your final chance!\n')
            #No handlers and no last resort, so 'No handlers' message
            logging.lastResort = None
            sys.stderr = sio = io.StringIO()
            root.warning('This is your final chance!')
            self.assertEqual(sio.getvalue(), 'No handlers could be found for logger "root"\n')
            # 'No handlers' message only printed once
            sys.stderr = sio = io.StringIO()
            root.warning('This is your final chance!')
            self.assertEqual(sio.getvalue(), '')
            root.manager.emittedNoHandlerWarning = False
            #If raiseExceptions is False, no message is printed
            logging.raiseExceptions = False
            sys.stderr = sio = io.StringIO()
            root.warning('This is your final chance!')
            self.assertEqual(sio.getvalue(), '')
        finally:
            sys.stderr = old_stderr
            root.addHandler(self.root_hdlr)
            logging.lastResort = old_lastresort
            logging.raiseExceptions = old_raise_exceptions 
Example 23
Project: ironpython3   Author: IronLanguages   File: test_logging.py    License: Apache License 2.0 5 votes vote down vote up
def setUp(self):
        super(ShutdownTest, self).setUp()
        self.called = []

        raise_exceptions = logging.raiseExceptions
        self.addCleanup(setattr, logging, 'raiseExceptions', raise_exceptions) 
Example 24
Project: ironpython3   Author: IronLanguages   File: test_logging.py    License: Apache License 2.0 5 votes vote down vote up
def test_with_other_error_in_acquire_without_raise(self):
        logging.raiseExceptions = False
        self._test_with_failure_in_method('acquire', IndexError) 
Example 25
Project: ironpython3   Author: IronLanguages   File: test_logging.py    License: Apache License 2.0 5 votes vote down vote up
def test_with_other_error_in_flush_without_raise(self):
        logging.raiseExceptions = False
        self._test_with_failure_in_method('flush', IndexError) 
Example 26
Project: ironpython3   Author: IronLanguages   File: test_logging.py    License: Apache License 2.0 5 votes vote down vote up
def test_with_other_error_in_acquire_with_raise(self):
        logging.raiseExceptions = True
        self.assertRaises(IndexError, self._test_with_failure_in_method,
                          'acquire', IndexError) 
Example 27
Project: ironpython3   Author: IronLanguages   File: test_logging.py    License: Apache License 2.0 5 votes vote down vote up
def test_with_other_error_in_flush_with_raise(self):
        logging.raiseExceptions = True
        self.assertRaises(IndexError, self._test_with_failure_in_method,
                          'flush', IndexError) 
Example 28
Project: ironpython3   Author: IronLanguages   File: test_logging.py    License: Apache License 2.0 5 votes vote down vote up
def test_with_other_error_in_close_with_raise(self):
        logging.raiseExceptions = True
        self.assertRaises(IndexError, self._test_with_failure_in_method,
                          'close', IndexError) 
Example 29
Project: ironpython3   Author: IronLanguages   File: test_logging.py    License: Apache License 2.0 5 votes vote down vote up
def test_log_invalid_level_with_raise(self):
        with swap_attr(logging, 'raiseExceptions', True):
            self.assertRaises(TypeError, self.logger.log, '10', 'test message') 
Example 30
Project: ironpython3   Author: IronLanguages   File: test_logging.py    License: Apache License 2.0 5 votes vote down vote up
def test_log_invalid_level_no_raise(self):
        with swap_attr(logging, 'raiseExceptions', False):
            self.logger.log('10', 'test message')  # no exception happens