Python logging.disable() Examples

The following are 30 code examples for showing how to use logging.disable(). 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: ripozo   Author: vertical-knowledge   File: adapters.py    License: GNU General Public License v2.0 6 votes vote down vote up
def setUp(self):
        logging.disable('DEBUG')

        class MyManager(InMemoryManager):
            _fields = ('id', 'first', 'second',)
            _field_validators = {
                'first': fields.IntegerField('first', required=True),
                'second': fields.IntegerField('second', required=True)
            }

        class MyClass(CRUDL):
            resource_name = 'myresource'
            manager = MyManager()

        self.resource_class = MyClass
        self.manager = MyClass.manager
        for i in six.moves.range(100):
            self.manager.objects[i] = dict(id=i, first=1, second=2)
        self.resource = MyClass.retrieve_list(RequestContainer()) 
Example 2
Project: ripozo   Author: vertical-knowledge   File: restmixins.py    License: GNU General Public License v2.0 6 votes vote down vote up
def setUp(self):
        logging.disable('DEBUG')

        class MyManager(InMemoryManager):
            _fields = ('id', 'first', 'second',)
            _field_validators = {
                'first': fields.IntegerField('first', required=True),
                'second': fields.IntegerField('second', required=True)
            }

        class MyClass(CRUDL):
            manager = MyManager()
            resource_name = 'myresource'

        self.resource_class = MyClass
        self.manager = MyClass.manager 
Example 3
Project: ripozo   Author: vertical-knowledge   File: end_to_end.py    License: GNU General Public License v2.0 6 votes vote down vote up
def setUp(self):
        logging.disable('DEBUG')

        class MyManager(InMemoryManager):
            _fields = ('id', 'first', 'second',)
            _field_validators = {
                'first': fields.IntegerField('first', required=True),
                'second': fields.IntegerField('second', required=True)
            }

        class MyClass(CRUDL):
            resource_name = 'myresource'
            manager = MyManager()

        self.resource_class = MyClass
        self.manager = MyClass.manager
        for i in six.moves.range(100):
            self.manager.objects[i] = dict(id=i, first=1, second=2)
        self.dispatcher = FakeDispatcher()
        self.dispatcher.register_adapters(SirenAdapter, HalAdapter, BoringJSONAdapter) 
Example 4
Project: ServerlessCrawler-VancouverRealState   Author: MarcelloLins   File: test_soup.py    License: MIT License 6 votes vote down vote up
def test_ascii_in_unicode_out(self):
        # ASCII input is converted to Unicode. The original_encoding
        # attribute is set to 'utf-8', a superset of ASCII.
        chardet = bs4.dammit.chardet_dammit
        logging.disable(logging.WARNING)
        try:
            def noop(str):
                return None
            # Disable chardet, which will realize that the ASCII is ASCII.
            bs4.dammit.chardet_dammit = noop
            ascii = b"<foo>a</foo>"
            soup_from_ascii = self.soup(ascii)
            unicode_output = soup_from_ascii.decode()
            self.assertTrue(isinstance(unicode_output, unicode))
            self.assertEqual(unicode_output, self.document_for(ascii.decode()))
            self.assertEqual(soup_from_ascii.original_encoding.lower(), "utf-8")
        finally:
            logging.disable(logging.NOTSET)
            bs4.dammit.chardet_dammit = chardet 
Example 5
Project: ServerlessCrawler-VancouverRealState   Author: MarcelloLins   File: test_soup.py    License: MIT License 6 votes vote down vote up
def test_ascii_in_unicode_out(self):
        # ASCII input is converted to Unicode. The original_encoding
        # attribute is set to 'utf-8', a superset of ASCII.
        chardet = bs4.dammit.chardet_dammit
        logging.disable(logging.WARNING)
        try:
            def noop(str):
                return None
            # Disable chardet, which will realize that the ASCII is ASCII.
            bs4.dammit.chardet_dammit = noop
            ascii = b"<foo>a</foo>"
            soup_from_ascii = self.soup(ascii)
            unicode_output = soup_from_ascii.decode()
            self.assertTrue(isinstance(unicode_output, unicode))
            self.assertEqual(unicode_output, self.document_for(ascii.decode()))
            self.assertEqual(soup_from_ascii.original_encoding.lower(), "utf-8")
        finally:
            logging.disable(logging.NOTSET)
            bs4.dammit.chardet_dammit = chardet 
Example 6
Project: ServerlessCrawler-VancouverRealState   Author: MarcelloLins   File: test_soup.py    License: MIT License 6 votes vote down vote up
def test_ascii_in_unicode_out(self):
        # ASCII input is converted to Unicode. The original_encoding
        # attribute is set to 'utf-8', a superset of ASCII.
        chardet = bs4.dammit.chardet_dammit
        logging.disable(logging.WARNING)
        try:
            def noop(str):
                return None
            # Disable chardet, which will realize that the ASCII is ASCII.
            bs4.dammit.chardet_dammit = noop
            ascii = b"<foo>a</foo>"
            soup_from_ascii = self.soup(ascii)
            unicode_output = soup_from_ascii.decode()
            self.assertTrue(isinstance(unicode_output, unicode))
            self.assertEqual(unicode_output, self.document_for(ascii.decode()))
            self.assertEqual(soup_from_ascii.original_encoding.lower(), "utf-8")
        finally:
            logging.disable(logging.NOTSET)
            bs4.dammit.chardet_dammit = chardet 
Example 7
Project: flumine   Author: liampauling   File: test_trade.py    License: MIT License 6 votes vote down vote up
def setUp(self) -> None:
        logging.disable(logging.CRITICAL)
        self.mock_strategy = mock.Mock()
        self.mock_fill_kill = mock.Mock()
        self.mock_offset = mock.Mock()
        self.mock_green = mock.Mock()
        self.mock_stop = mock.Mock()
        self.notes = collections.OrderedDict({"trigger": 123})
        self.trade = Trade(
            "1.234",
            567,
            1.0,
            self.mock_strategy,
            self.notes,
            self.mock_fill_kill,
            self.mock_offset,
            self.mock_green,
            self.mock_stop,
        ) 
Example 8
Project: pledgeservice   Author: MayOneUS   File: test_soup.py    License: Apache License 2.0 6 votes vote down vote up
def test_ascii_in_unicode_out(self):
        # ASCII input is converted to Unicode. The original_encoding
        # attribute is set to 'utf-8', a superset of ASCII.
        chardet = bs4.dammit.chardet_dammit
        logging.disable(logging.WARNING)
        try:
            def noop(str):
                return None
            # Disable chardet, which will realize that the ASCII is ASCII.
            bs4.dammit.chardet_dammit = noop
            ascii = b"<foo>a</foo>"
            soup_from_ascii = self.soup(ascii)
            unicode_output = soup_from_ascii.decode()
            self.assertTrue(isinstance(unicode_output, unicode))
            self.assertEqual(unicode_output, self.document_for(ascii.decode()))
            self.assertEqual(soup_from_ascii.original_encoding.lower(), "utf-8")
        finally:
            logging.disable(logging.NOTSET)
            bs4.dammit.chardet_dammit = chardet 
Example 9
Project: lrbd   Author: swiftgist   File: test_luns.py    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
def test_cmd_for_rbd(self):

        Runtime.config['backstore'] = "rbd"
        class mock_Luns(Luns):

            def _find(self):
                pass

        class mock_LunAssignment(object):
            def assign(self, target, tpg, image, lun):
                pass

            def assigned(self, target, image):
                pass

        logging.disable(logging.DEBUG)
        _la = mock_LunAssignment()
        self.l = mock_Luns(_la)
        print self.l.unassigned
        assert self.l.unassigned == [ ['targetcli', '/iscsi/iqn.xyz/tpg1/luns', 'create', '/backstores/rbd/rbd-archive'] ] 
Example 10
Project: locality-sensitive-hashing   Author: singhj   File: test_soup.py    License: MIT License 6 votes vote down vote up
def test_ascii_in_unicode_out(self):
        # ASCII input is converted to Unicode. The original_encoding
        # attribute is set to 'utf-8', a superset of ASCII.
        chardet = bs4.dammit.chardet_dammit
        logging.disable(logging.WARNING)
        try:
            def noop(str):
                return None
            # Disable chardet, which will realize that the ASCII is ASCII.
            bs4.dammit.chardet_dammit = noop
            ascii = b"<foo>a</foo>"
            soup_from_ascii = self.soup(ascii)
            unicode_output = soup_from_ascii.decode()
            self.assertTrue(isinstance(unicode_output, unicode))
            self.assertEqual(unicode_output, self.document_for(ascii.decode()))
            self.assertEqual(soup_from_ascii.original_encoding.lower(), "utf-8")
        finally:
            logging.disable(logging.NOTSET)
            bs4.dammit.chardet_dammit = chardet 
Example 11
Project: koku   Author: project-koku   File: tests_middleware.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_race_condition_user_caching(self):
        """Test case for caching where another request may create the user in a race condition."""
        mock_request = self.request
        middleware = IdentityHeaderMiddleware()
        self.assertEquals(MD.USER_CACHE.maxsize, 5)  # Confirm that the size of the user cache has changed
        self.assertEquals(MD.USER_CACHE.currsize, 0)  # Confirm that the user cache is empty
        middleware.process_request(mock_request)
        self.assertEquals(MD.USER_CACHE.currsize, 1)
        self.assertTrue(hasattr(mock_request, "user"))
        customer = Customer.objects.get(account_id=self.customer.account_id)
        self.assertIsNotNone(customer)
        user = User.objects.get(username=self.user_data["username"])
        self.assertEquals(MD.USER_CACHE.currsize, 1)
        self.assertIsNotNone(user)
        IdentityHeaderMiddleware.create_user(
            username=self.user_data["username"],  # pylint: disable=W0212
            email=self.user_data["email"],
            customer=customer,
            request=mock_request,
        )
        self.assertEquals(MD.USER_CACHE.currsize, 1) 
Example 12
Project: koku   Author: project-koku   File: test_azure_report_processor.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_azure_process(self):
        """Test the processing of an uncompressed Azure file."""
        counts = {}

        report_db = self.accessor
        report_schema = report_db.report_schema
        for table_name in self.report_tables:
            table = getattr(report_schema, table_name)
            with schema_context(self.schema):
                count = table.objects.count()
            counts[table_name] = count
        logging.disable(logging.NOTSET)  # We are currently disabling all logging below CRITICAL in masu/__init__.py
        with self.assertLogs("masu.processor.azure.azure_report_processor", level="INFO") as logger:
            self.processor.process()
            self.assertIn("INFO:masu.processor.azure.azure_report_processor", logger.output[0])
            self.assertIn("costreport_a243c6f2-199f-4074-9a2c-40e671cf1584.csv", logger.output[0])

        for table_name in self.report_tables:
            table = getattr(report_schema, table_name)
            with schema_context(self.schema):
                count = table.objects.count()
            self.assertTrue(count > counts[table_name])
        self.assertFalse(os.path.exists(self.test_report)) 
Example 13
Project: koku   Author: project-koku   File: test_tasks.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_disk_status_logging(self, fake_downloader):
        """Test task for logging when temp directory exists."""
        logging.disable(logging.NOTSET)
        os.makedirs(Config.TMP_DIR, exist_ok=True)

        account = fake_arn(service="iam", generate_account_id=True)
        expected = "Available disk space"
        with self.assertLogs("masu.processor._tasks.download", level="INFO") as logger:
            _get_report_files(
                Mock(),
                customer_name=self.fake.word(),
                authentication=account,
                provider_type=Provider.PROVIDER_AWS,
                report_month=DateHelper().today,
                provider_uuid=self.aws_provider_uuid,
                billing_source=self.fake.word(),
                cache_key=self.fake.word(),
            )
            statement_found = False
            for log in logger.output:
                if expected in log:
                    statement_found = True
            self.assertTrue(statement_found)

        shutil.rmtree(Config.TMP_DIR, ignore_errors=True) 
Example 14
Project: koku   Author: project-koku   File: test_tasks.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_disk_status_logging_no_dir(self, fake_downloader):
        """Test task for logging when temp directory does not exist."""
        logging.disable(logging.NOTSET)

        Config.PVC_DIR = "/this/path/does/not/exist"

        account = fake_arn(service="iam", generate_account_id=True)
        expected = "Unable to find" + f" available disk space. {Config.PVC_DIR} does not exist"
        with self.assertLogs("masu.processor._tasks.download", level="INFO") as logger:
            _get_report_files(
                Mock(),
                customer_name=self.fake.word(),
                authentication=account,
                provider_type=Provider.PROVIDER_AWS,
                report_month=DateHelper().today,
                provider_uuid=self.aws_provider_uuid,
                billing_source=self.fake.word(),
                cache_key=self.fake.word(),
            )
            statement_found = False
            for log in logger.output:
                if expected in log:
                    statement_found = True
            self.assertTrue(statement_found) 
Example 15
Project: ipmisim   Author: rhtyd   File: ipmisim.py    License: Apache License 2.0 5 votes vote down vote up
def main():
    logging.disable(logging.NOTSET)
    logger.setLevel(logging.INFO)

    ch = logging.StreamHandler(sys.stdout)
    ch.setLevel(logging.DEBUG)
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    ch.setFormatter(formatter)
    logger.addHandler(ch)

    port = 9001
    if len(sys.argv) > 1:
        port = int(sys.argv[1])

    # Initialize context
    ctx = IpmiServerContext()

    try:
        ThreadedIpmiServer.allow_reuse_address = True
        server = ThreadedIpmiServer(('0.0.0.0', port), IpmiServer)
        logger.info("Started IPMI Server on 0.0.0.0:" + str(port))
        server.serve_forever()
    except KeyboardInterrupt:
        server.shutdown()
        server.server_close()
        sys.exit(0) 
Example 16
Project: controller   Author: deis   File: __init__.py    License: MIT License 5 votes vote down vote up
def run_tests(self, test_labels, extra_tests=None, **kwargs):
        """Run tests with all but critical log messages disabled."""
        # hide any log messages less than critical
        logging.disable(logging.ERROR)
        return super(SilentDjangoTestSuiteRunner, self).run_tests(
            test_labels, extra_tests, **kwargs) 
Example 17
Project: stoq   Author: PUNCH-Cyber   File: test_core.py    License: Apache License 2.0 5 votes vote down vote up
def setUp(self) -> None:
        logging.disable(logging.CRITICAL)
        self.generic_content = b'The quick brown fox'  # type: ignore 
Example 18
Project: stoq   Author: PUNCH-Cyber   File: test_core.py    License: Apache License 2.0 5 votes vote down vote up
def tearDown(self) -> None:
        logging.disable(logging.NOTSET) 
Example 19
Project: stoq   Author: PUNCH-Cyber   File: test_core.py    License: Apache License 2.0 5 votes vote down vote up
def test_connector_exception(self):
        s = Stoq(base_dir=utils.get_data_dir(), connectors=['dummy_connector'])
        dummy_connector = s.load_plugin('dummy_connector')
        dummy_connector.save = asynctest.create_autospec(
            dummy_connector.save, side_effect=RuntimeError('Unexpected exception')
        )
        logging.disable(logging.NOTSET)
        with self.assertLogs(level='ERROR') as cm:
            await s.scan(self.generic_content)
        self.assertTrue(
            cm.output[0].startswith(
                'ERROR:stoq:Failed to save results using dummy_connector'
            )
        )
        logging.disable(logging.CRITICAL) 
Example 20
Project: stoq   Author: PUNCH-Cyber   File: test_core.py    License: Apache License 2.0 5 votes vote down vote up
def test_provider_exception(self):
        s = Stoq(base_dir=utils.get_data_dir(), providers=['simple_provider'])
        simple_provider = s.load_plugin('simple_provider')
        simple_provider.RAISE_EXCEPTION = True
        logging.disable(logging.NOTSET)
        with self.assertLogs(level='ERROR') as cm:
            await s.run()
        self.assertTrue(
            cm.output[0].startswith('ERROR:stoq:Test exception, please ignore')
        )
        logging.disable(logging.CRITICAL) 
Example 21
Project: stoq   Author: PUNCH-Cyber   File: test_plugin_manager.py    License: Apache License 2.0 5 votes vote down vote up
def setUp(self) -> None:
        logging.disable(logging.CRITICAL) 
Example 22
Project: stoq   Author: PUNCH-Cyber   File: test_plugin_manager.py    License: Apache License 2.0 5 votes vote down vote up
def test_min_stoq_version(self):
        pm = StoqPluginManager([utils.get_invalid_plugins_dir()])
        # We have to override the fact that all log calls are disabled in setUp()
        # for the calls here to actually go through
        logging.disable(logging.NOTSET)
        with self.assertLogs(level='WARNING'):
            plugin = pm.load_plugin('incompatible_min_stoq_version')
        self.assertIsNotNone(plugin) 
Example 23
Project: qutebrowser   Author: qutebrowser   File: log.py    License: GNU General Public License v3.0 5 votes vote down vote up
def vdebug(self: logging.Logger,
           msg: str,
           *args: typing.Any,
           **kwargs: typing.Any) -> None:
    """Log with a VDEBUG level.

    VDEBUG is used when a debug message is rather verbose, and probably of
    little use to the end user or for post-mortem debugging, i.e. the content
    probably won't change unless the code changes.
    """
    if self.isEnabledFor(VDEBUG_LEVEL):
        # pylint: disable=protected-access
        self._log(VDEBUG_LEVEL, msg, args, **kwargs)
        # pylint: enable=protected-access 
Example 24
Project: qutebrowser   Author: qutebrowser   File: log.py    License: GNU General Public License v3.0 5 votes vote down vote up
def init_log(args: argparse.Namespace) -> None:
    """Init loggers based on the argparse namespace passed."""
    level = (args.loglevel or "info").upper()
    try:
        numeric_level = getattr(logging, level)
    except AttributeError:
        raise ValueError("Invalid log level: {}".format(args.loglevel))

    if numeric_level > logging.DEBUG and args.debug:
        numeric_level = logging.DEBUG

    console, ram = _init_handlers(numeric_level, args.color, args.force_color,
                                  args.json_logging, args.loglines)
    root = logging.getLogger()
    global console_filter
    if console is not None:
        console_filter = LogFilter.parse(args.logfilter)
        console.addFilter(console_filter)
        root.addHandler(console)
    if ram is not None:
        root.addHandler(ram)
    else:
        # If we add no handler, we shouldn't process non visible logs at all
        #
        # disable blocks the current level (while setHandler shows the current
        # level), so -1 to avoid blocking handled messages.
        logging.disable(numeric_level - 1)

    global _log_inited, _args
    _args = args
    root.setLevel(logging.NOTSET)
    logging.captureWarnings(True)
    _init_py_warnings()
    QtCore.qInstallMessageHandler(qt_message_handler)
    _log_inited = True 
Example 25
Project: qutebrowser   Author: qutebrowser   File: log.py    License: GNU General Public License v3.0 5 votes vote down vote up
def ignore_py_warnings(**kwargs: typing.Any) -> typing.Iterator[None]:
    """Contextmanager to temporarily disable certain Python warnings."""
    warnings.filterwarnings('ignore', **kwargs)
    yield
    if _log_inited:
        _init_py_warnings() 
Example 26
Project: ServerlessCrawler-VancouverRealState   Author: MarcelloLins   File: test_soup.py    License: MIT License 5 votes vote down vote up
def test_last_ditch_entity_replacement(self):
        # This is a UTF-8 document that contains bytestrings
        # completely incompatible with UTF-8 (ie. encoded with some other
        # encoding).
        #
        # Since there is no consistent encoding for the document,
        # Unicode, Dammit will eventually encode the document as UTF-8
        # and encode the incompatible characters as REPLACEMENT
        # CHARACTER.
        #
        # If chardet is installed, it will detect that the document
        # can be converted into ISO-8859-1 without errors. This happens
        # to be the wrong encoding, but it is a consistent encoding, so the
        # code we're testing here won't run.
        #
        # So we temporarily disable chardet if it's present.
        doc = b"""\357\273\277<?xml version="1.0" encoding="UTF-8"?>
<html><b>\330\250\330\252\330\261</b>
<i>\310\322\321\220\312\321\355\344</i></html>"""
        chardet = bs4.dammit.chardet_dammit
        logging.disable(logging.WARNING)
        try:
            def noop(str):
                return None
            bs4.dammit.chardet_dammit = noop
            dammit = UnicodeDammit(doc)
            self.assertEqual(True, dammit.contains_replacement_characters)
            self.assertTrue(u"\ufffd" in dammit.unicode_markup)

            soup = BeautifulSoup(doc, "html.parser")
            self.assertTrue(soup.contains_replacement_characters)
        finally:
            logging.disable(logging.NOTSET)
            bs4.dammit.chardet_dammit = chardet 
Example 27
Project: ServerlessCrawler-VancouverRealState   Author: MarcelloLins   File: test_soup.py    License: MIT License 5 votes vote down vote up
def test_last_ditch_entity_replacement(self):
        # This is a UTF-8 document that contains bytestrings
        # completely incompatible with UTF-8 (ie. encoded with some other
        # encoding).
        #
        # Since there is no consistent encoding for the document,
        # Unicode, Dammit will eventually encode the document as UTF-8
        # and encode the incompatible characters as REPLACEMENT
        # CHARACTER.
        #
        # If chardet is installed, it will detect that the document
        # can be converted into ISO-8859-1 without errors. This happens
        # to be the wrong encoding, but it is a consistent encoding, so the
        # code we're testing here won't run.
        #
        # So we temporarily disable chardet if it's present.
        doc = b"""\357\273\277<?xml version="1.0" encoding="UTF-8"?>
<html><b>\330\250\330\252\330\261</b>
<i>\310\322\321\220\312\321\355\344</i></html>"""
        chardet = bs4.dammit.chardet_dammit
        logging.disable(logging.WARNING)
        try:
            def noop(str):
                return None
            bs4.dammit.chardet_dammit = noop
            dammit = UnicodeDammit(doc)
            self.assertEqual(True, dammit.contains_replacement_characters)
            self.assertTrue(u"\ufffd" in dammit.unicode_markup)

            soup = BeautifulSoup(doc, "html.parser")
            self.assertTrue(soup.contains_replacement_characters)
        finally:
            logging.disable(logging.NOTSET)
            bs4.dammit.chardet_dammit = chardet 
Example 28
Project: moler   Author: nokia   File: loghelper.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def disabled_logging(from_level_and_below=logging.INFO):
    logging.disable(from_level_and_below)
    yield
    logging.disable(logging.NOTSET) 
Example 29
Project: pycounter   Author: pitthsls   File: test_sushi.py    License: MIT License 5 votes vote down vote up
def test_bogus_xml():
    """Test dealing with broken XML"""
    logging.disable(logging.CRITICAL)
    with HTTMock(bogus_mock):
        with pytest.raises(pycounter.exceptions.SushiException):
            sushi.get_report(
                "http://www.example.com/bogus",
                datetime.date(2015, 1, 1),
                datetime.date(2015, 1, 31),
            ) 
Example 30
Project: flumine   Author: liampauling   File: test_worker.py    License: MIT License 5 votes vote down vote up
def setUp(self) -> None:
        logging.disable(logging.CRITICAL)