Python logging.raiseExceptions() Examples

The following are 30 code examples of logging.raiseExceptions(). 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 also want to check out all available functions/classes of the module logging , or try the search function .
Example #1
Source File: py23.py    From Emoji-Tools with 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 #2
Source File: test_logging.py    From ironpython3 with 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 #3
Source File: parser.py    From kll with 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 #4
Source File: test_logging.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 6 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 #5
Source File: test_logging.py    From Project-New-Reign---Nemesis-Main with 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 #6
Source File: test_logging.py    From ironpython3 with 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 #7
Source File: test_logging.py    From ironpython3 with 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 #8
Source File: test_logging.py    From ironpython3 with 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 #9
Source File: test_logging.py    From ironpython3 with 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 #10
Source File: test_logging.py    From ironpython3 with 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 #11
Source File: test_logging.py    From ironpython3 with 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 
Example #12
Source File: app.py    From resilient-python-api with MIT License 5 votes vote down vote up
def config_logging(self, logdir, loglevel, logfile):
        """ set up some logging """
        global LOG_PATH, LOG, logging_initialized

        LOG_PATH = os.path.join(logdir, logfile)
        LOG_PATH = os.path.expanduser(LOG_PATH)
        LOG = logging.getLogger(__name__)

        # Only do this once! (mostly for pytest)
        if logging_initialized:
            LOG.info("Logging already initialized.")
            return
        logging_initialized = True

        # Ignore syslog errors from message-too-long
        logging.raiseExceptions = False

        try:
            numeric_level = getattr(logging, loglevel)
            logging.getLogger().setLevel(numeric_level)
        except AttributeError as e:
            logging.getLogger().setLevel(logging.INFO)
            LOG.warning("Invalid logging level specified. Using INFO level")

        if logging.getLogger().getEffectiveLevel() == logging.DEBUG:
            self += Debugger()

        file_handler = RotatingFileHandler(LOG_PATH, maxBytes=10000000,
                                           backupCount=10)
        file_handler.setFormatter(logging.Formatter(self.FILE_LOG_FORMAT))
        logging.getLogger().addHandler(file_handler)
        syslog = logging.handlers.SysLogHandler()
        syslog.setFormatter(logging.Formatter(self.SYSLOG_LOG_FORMAT))
        logging.getLogger().addHandler(syslog)
        stderr = logging.StreamHandler()
        stderr.setFormatter(logging.Formatter(self.STDERR_LOG_FORMAT))
        logging.getLogger().addHandler(stderr)
        # Add password redacting filter for logging.
        syslog.addFilter(RedactingFilter())
        file_handler.addFilter(RedactingFilter())
        stderr.addFilter(RedactingFilter()) 
Example #13
Source File: vlog.py    From ryu with Apache License 2.0 5 votes vote down vote up
def init(log_file=None):
        """Intializes the Vlog module.  Causes Vlog to write to 'log_file' if
        not None.  Should be called after all Vlog objects have been created.
        No logging will occur until this function is called."""

        if Vlog.__inited:
            return

        Vlog.__inited = True
        logging.raiseExceptions = False
        Vlog.__log_file = log_file
        for f in FACILITIES:
            logger = logging.getLogger(f)
            logger.setLevel(logging.DEBUG)

            try:
                if f == "console":
                    logger.addHandler(logging.StreamHandler(sys.stderr))
                elif f == "syslog":
                    logger.addHandler(logging.handlers.SysLogHandler(
                        address="/dev/log",
                        facility=logging.handlers.SysLogHandler.LOG_DAEMON))
                elif f == "file" and Vlog.__log_file:
                    Vlog.__file_handler = logging.FileHandler(Vlog.__log_file)
                    logger.addHandler(Vlog.__file_handler)
            except (IOError, socket.error):
                logger.setLevel(logging.CRITICAL)

        ovs.unixctl.command_register("vlog/reopen", "", 0, 0,
                                     Vlog._unixctl_vlog_reopen, None)
        ovs.unixctl.command_register("vlog/set", "spec", 1, sys.maxint,
                                     Vlog._unixctl_vlog_set, None)
        ovs.unixctl.command_register("vlog/list", "", 0, 0,
                                     Vlog._unixctl_vlog_list, None) 
Example #14
Source File: test_logging.py    From ironpython3 with 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 #15
Source File: test_logging.py    From Project-New-Reign---Nemesis-Main with 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 #16
Source File: test_logging.py    From Project-New-Reign---Nemesis-Main with 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 #17
Source File: test_logging.py    From Project-New-Reign---Nemesis-Main with 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 #18
Source File: test_logging.py    From Project-New-Reign---Nemesis-Main with 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 #19
Source File: test_logging.py    From Project-New-Reign---Nemesis-Main with 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 #20
Source File: test_logging.py    From Project-New-Reign---Nemesis-Main with 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 #21
Source File: test_logging.py    From Project-New-Reign---Nemesis-Main with 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 #22
Source File: test_logging.py    From Project-New-Reign---Nemesis-Main with 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 #23
Source File: log.py    From workload-automation with Apache License 2.0 5 votes vote down vote up
def init(verbosity=logging.INFO, color=True, indent_with=4,
         regular_fmt='%(levelname)-8s %(message)s',
         verbose_fmt='%(asctime)s %(levelname)-8s %(name)10.10s: %(message)s',
         debug=False):
    global _indent_width, _console_handler, _init_handler
    _indent_width = indent_with
    signal.log_error_func = lambda m: log_error(m, signal.logger)

    root_logger = logging.getLogger()
    root_logger.setLevel(logging.DEBUG)

    error_handler = ErrorSignalHandler(logging.DEBUG)
    root_logger.addHandler(error_handler)

    _console_handler = logging.StreamHandler()
    if color:
        formatter = ColorFormatter
    else:
        formatter = LineFormatter
    if verbosity:
        _console_handler.setLevel(logging.DEBUG)
        _console_handler.setFormatter(formatter(verbose_fmt))
    else:
        _console_handler.setLevel(logging.INFO)
        _console_handler.setFormatter(formatter(regular_fmt))
    root_logger.addHandler(_console_handler)

    buffer_capacity = os.getenv('WA_LOG_BUFFER_CAPACITY',
                                DEFAULT_INIT_BUFFER_CAPACITY)
    _init_handler = InitHandler(buffer_capacity)
    _init_handler.setLevel(logging.DEBUG)
    root_logger.addHandler(_init_handler)

    logging.basicConfig(level=logging.DEBUG)
    if not debug:
        logging.raiseExceptions = False

    logger = logging.getLogger('CGroups')
    logger.info = logger.debug 
Example #24
Source File: test_logging.py    From ironpython3 with 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 #25
Source File: logging.py    From pytest with 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 #26
Source File: test_logging.py    From Fluid-Designer with 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 #27
Source File: test_logging.py    From Fluid-Designer with 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 #28
Source File: test_logging.py    From Fluid-Designer with 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 #29
Source File: test_logging.py    From Fluid-Designer with 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 #30
Source File: test_logging.py    From Fluid-Designer with 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)