Python logging.captureWarnings() Examples

The following are 30 code examples for showing how to use logging.captureWarnings(). 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: pydarkstar   Author: AdamGagorik   File: logutils.py    License: MIT License 6 votes vote down vote up
def capture(capture_warnings=True, fail=False):
    """
    Log exceptions and warnings.
    """
    default_warning_format = warnings.formatwarning
    try:
        if capture_warnings:
            warnings.formatwarning = custom_warning_format
            logging.captureWarnings(True)
        try:
            yield
        except Exception as e:
            logging.exception('caught unhandled excetion')
            if fail:
                if not isinstance(e, Warning):
                    raise RuntimeError('application failure')
    finally:
        if capture_warnings:
            warnings.formatwarning = default_warning_format
            logging.captureWarnings(False) 
Example 2
Project: GTDWeb   Author: lanbing510   File: log.py    License: GNU General Public License v2.0 6 votes vote down vote up
def configure_logging(logging_config, logging_settings):
    if not sys.warnoptions:
        # Route warnings through python logging
        logging.captureWarnings(True)
        # RemovedInNextVersionWarning is a subclass of DeprecationWarning which
        # is hidden by default, hence we force the "default" behavior
        warnings.simplefilter("default", RemovedInNextVersionWarning)

    if logging_config:
        # First find the logging configuration function ...
        logging_config_func = import_string(logging_config)

        dictConfig(DEFAULT_LOGGING)

        # ... then invoke it with the logging settings
        if logging_settings:
            logging_config_func(logging_settings) 
Example 3
Project: ironpython2   Author: IronLanguages   File: test_logging.py    License: Apache License 2.0 6 votes vote down vote up
def test_warnings(self):
        with warnings.catch_warnings():
            logging.captureWarnings(True)
            try:
                warnings.filterwarnings("always", category=UserWarning)
                file = cStringIO.StringIO()
                h = logging.StreamHandler(file)
                logger = logging.getLogger("py.warnings")
                logger.addHandler(h)
                warnings.warn("I'm warning you...")
                logger.removeHandler(h)
                s = file.getvalue()
                h.close()
                self.assertTrue(s.find("UserWarning: I'm warning you...\n") > 0)

                #See if an explicit file uses the original implementation
                file = cStringIO.StringIO()
                warnings.showwarning("Explicit", UserWarning, "dummy.py", 42,
                                        file, "Dummy line")
                s = file.getvalue()
                file.close()
                self.assertEqual(s,
                        "dummy.py:42: UserWarning: Explicit\n  Dummy line\n")
            finally:
                logging.captureWarnings(False) 
Example 4
Project: bioforum   Author: reBiocoder   File: __main__.py    License: MIT License 6 votes vote down vote up
def run():  # pragma: no cover
    """Run Markdown from the command line."""

    # Parse options and adjust logging level if necessary
    options, logging_level = parse_options()
    if not options:
        sys.exit(2)
    logger.setLevel(logging_level)
    console_handler = logging.StreamHandler()
    logger.addHandler(console_handler)
    if logging_level <= WARNING:
        # Ensure deprecation warnings get displayed
        warnings.filterwarnings('default')
        logging.captureWarnings(True)
        warn_logger = logging.getLogger('py.warnings')
        warn_logger.addHandler(console_handler)

    # Run
    markdown.markdownFromFile(**options) 
Example 5
Project: BinderFilter   Author: dxwu   File: test_logging.py    License: MIT License 6 votes vote down vote up
def test_warnings(self):
        with warnings.catch_warnings():
            logging.captureWarnings(True)
            try:
                warnings.filterwarnings("always", category=UserWarning)
                file = cStringIO.StringIO()
                h = logging.StreamHandler(file)
                logger = logging.getLogger("py.warnings")
                logger.addHandler(h)
                warnings.warn("I'm warning you...")
                logger.removeHandler(h)
                s = file.getvalue()
                h.close()
                self.assertTrue(s.find("UserWarning: I'm warning you...\n") > 0)

                #See if an explicit file uses the original implementation
                file = cStringIO.StringIO()
                warnings.showwarning("Explicit", UserWarning, "dummy.py", 42,
                                        file, "Dummy line")
                s = file.getvalue()
                file.close()
                self.assertEqual(s,
                        "dummy.py:42: UserWarning: Explicit\n  Dummy line\n")
            finally:
                logging.captureWarnings(False) 
Example 6
Project: oss-ftp   Author: aliyun   File: test_logging.py    License: MIT License 6 votes vote down vote up
def test_warnings(self):
        with warnings.catch_warnings():
            logging.captureWarnings(True)
            try:
                warnings.filterwarnings("always", category=UserWarning)
                file = cStringIO.StringIO()
                h = logging.StreamHandler(file)
                logger = logging.getLogger("py.warnings")
                logger.addHandler(h)
                warnings.warn("I'm warning you...")
                logger.removeHandler(h)
                s = file.getvalue()
                h.close()
                self.assertTrue(s.find("UserWarning: I'm warning you...\n") > 0)

                #See if an explicit file uses the original implementation
                file = cStringIO.StringIO()
                warnings.showwarning("Explicit", UserWarning, "dummy.py", 42,
                                        file, "Dummy line")
                s = file.getvalue()
                file.close()
                self.assertEqual(s,
                        "dummy.py:42: UserWarning: Explicit\n  Dummy line\n")
            finally:
                logging.captureWarnings(False) 
Example 7
Project: Fluid-Designer   Author: Microvellum   File: test_logging.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_warnings(self):
        with warnings.catch_warnings():
            logging.captureWarnings(True)
            self.addCleanup(logging.captureWarnings, False)
            warnings.filterwarnings("always", category=UserWarning)
            stream = io.StringIO()
            h = logging.StreamHandler(stream)
            logger = logging.getLogger("py.warnings")
            logger.addHandler(h)
            warnings.warn("I'm warning you...")
            logger.removeHandler(h)
            s = stream.getvalue()
            h.close()
            self.assertGreater(s.find("UserWarning: I'm warning you...\n"), 0)

            #See if an explicit file uses the original implementation
            a_file = io.StringIO()
            warnings.showwarning("Explicit", UserWarning, "dummy.py", 42,
                                 a_file, "Dummy line")
            s = a_file.getvalue()
            a_file.close()
            self.assertEqual(s,
                "dummy.py:42: UserWarning: Explicit\n  Dummy line\n") 
Example 8
Project: bandit   Author: PyCQA   File: main.py    License: Apache License 2.0 6 votes vote down vote up
def _init_logger(log_level=logging.INFO, log_format=None):
    '''Initialize the logger

    :param debug: Whether to enable debug mode
    :return: An instantiated logging instance
    '''
    LOG.handlers = []

    if not log_format:
        # default log format
        log_format_string = constants.log_format_string
    else:
        log_format_string = log_format

    logging.captureWarnings(True)

    LOG.setLevel(log_level)
    handler = logging.StreamHandler(sys.stderr)
    handler.setFormatter(logging.Formatter(log_format_string))
    LOG.addHandler(handler)
    LOG.debug("logging initialized") 
Example 9
Project: ironpython3   Author: IronLanguages   File: test_logging.py    License: Apache License 2.0 6 votes vote down vote up
def test_warnings(self):
        with warnings.catch_warnings():
            logging.captureWarnings(True)
            self.addCleanup(logging.captureWarnings, False)
            warnings.filterwarnings("always", category=UserWarning)
            stream = io.StringIO()
            h = logging.StreamHandler(stream)
            logger = logging.getLogger("py.warnings")
            logger.addHandler(h)
            warnings.warn("I'm warning you...")
            logger.removeHandler(h)
            s = stream.getvalue()
            h.close()
            self.assertGreater(s.find("UserWarning: I'm warning you...\n"), 0)

            #See if an explicit file uses the original implementation
            a_file = io.StringIO()
            warnings.showwarning("Explicit", UserWarning, "dummy.py", 42,
                                 a_file, "Dummy line")
            s = a_file.getvalue()
            a_file.close()
            self.assertEqual(s,
                "dummy.py:42: UserWarning: Explicit\n  Dummy line\n") 
Example 10
Project: rally   Author: elastic   File: log.py    License: Apache License 2.0 6 votes vote down vote up
def post_configure_actor_logging():
    """
    Reconfigures all loggers in actor processes.

    See https://groups.google.com/forum/#!topic/thespianpy/FntU9umtvhc for the rationale.
    """
    # see configure_logging()
    logging.captureWarnings(True)

    # at this point we can assume that a log configuration exists. It has been created already during startup.
    logger_configuration = load_configuration()
    if "root" in logger_configuration and "level" in logger_configuration["root"]:
        root_logger = logging.getLogger()
        root_logger.setLevel(logger_configuration["root"]["level"])

    if "loggers" in logger_configuration:
        for lgr, cfg in load_configuration()["loggers"].items():
            if "level" in cfg:
                logging.getLogger(lgr).setLevel(cfg["level"]) 
Example 11
Project: openhgsenti   Author: drexly   File: log.py    License: Apache License 2.0 6 votes vote down vote up
def configure_logging(logging_config, logging_settings):
    if not sys.warnoptions:
        # Route warnings through python logging
        logging.captureWarnings(True)
        # RemovedInNextVersionWarning is a subclass of DeprecationWarning which
        # is hidden by default, hence we force the "default" behavior
        warnings.simplefilter("default", RemovedInNextVersionWarning)

    if logging_config:
        # First find the logging configuration function ...
        logging_config_func = import_string(logging_config)

        logging.config.dictConfig(DEFAULT_LOGGING)

        # ... then invoke it with the logging settings
        if logging_settings:
            logging_config_func(logging_settings) 
Example 12
Project: gcblue   Author: gcblue   File: test_logging.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_warnings(self):
        with warnings.catch_warnings():
            logging.captureWarnings(True)
            try:
                warnings.filterwarnings("always", category=UserWarning)
                file = cStringIO.StringIO()
                h = logging.StreamHandler(file)
                logger = logging.getLogger("py.warnings")
                logger.addHandler(h)
                warnings.warn("I'm warning you...")
                logger.removeHandler(h)
                s = file.getvalue()
                h.close()
                self.assertTrue(s.find("UserWarning: I'm warning you...\n") > 0)

                #See if an explicit file uses the original implementation
                file = cStringIO.StringIO()
                warnings.showwarning("Explicit", UserWarning, "dummy.py", 42,
                                        file, "Dummy line")
                s = file.getvalue()
                file.close()
                self.assertEqual(s,
                        "dummy.py:42: UserWarning: Explicit\n  Dummy line\n")
            finally:
                logging.captureWarnings(False) 
Example 13
Project: iterativeWGCNA   Author: cstoeckert   File: iterativeWGCNA.py    License: GNU General Public License v2.0 6 votes vote down vote up
def __initialize_log(self, logType='run'):
        '''
        initialize log by setting path and file format
        '''
        logName = 'iterativeWGCNA.log'
        if logType == 'summary':
            logName = 'summarize-network-' + logName
        elif logType == 'merge':
            logName = 'adjust-merge-' + str(self.args.finalMergeCutHeight) + '-' + logName

        logging.basicConfig(filename=self.args.workingDir + '/' + logName,
                            filemode='w', format='%(levelname)s: %(message)s',
                            level=logging.DEBUG)

        logging.captureWarnings(True)
        self.logger = logging.getLogger(__name__) 
Example 14
def test_warnings(self):
        with warnings.catch_warnings():
            logging.captureWarnings(True)
            self.addCleanup(logging.captureWarnings, False)
            warnings.filterwarnings("always", category=UserWarning)
            stream = io.StringIO()
            h = logging.StreamHandler(stream)
            logger = logging.getLogger("py.warnings")
            logger.addHandler(h)
            warnings.warn("I'm warning you...")
            logger.removeHandler(h)
            s = stream.getvalue()
            h.close()
            self.assertGreater(s.find("UserWarning: I'm warning you...\n"), 0)

            #See if an explicit file uses the original implementation
            a_file = io.StringIO()
            warnings.showwarning("Explicit", UserWarning, "dummy.py", 42,
                                 a_file, "Dummy line")
            s = a_file.getvalue()
            a_file.close()
            self.assertEqual(s,
                "dummy.py:42: UserWarning: Explicit\n  Dummy line\n") 
Example 15
Project: style_transfer   Author: crowsonkb   File: log_utils.py    License: MIT License 6 votes vote down vote up
def setup_logger(name=None, level=None, formatter_opts=None):
    """Sets up pretty logging using LogFormatter."""
    if formatter_opts is None:
        formatter_opts = {}
    logging.captureWarnings(True)
    logger = logging.getLogger(name)
    if 'DEBUG' in os.environ:
        level = logging.DEBUG
    elif level is None:
        level = logging.INFO
    logger.setLevel(level)
    channel = logging.StreamHandler()
    formatter = LogFormatter(**formatter_opts)
    channel.setFormatter(formatter)
    logger.addHandler(channel)
    return logger 
Example 16
Project: CTFCrackTools-V2   Author: Acmesec   File: test_logging.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_warnings(self):
        with warnings.catch_warnings():
            logging.captureWarnings(True)
            try:
                warnings.filterwarnings("always", category=UserWarning)
                file = cStringIO.StringIO()
                h = logging.StreamHandler(file)
                logger = logging.getLogger("py.warnings")
                logger.addHandler(h)
                warnings.warn("I'm warning you...")
                logger.removeHandler(h)
                s = file.getvalue()
                h.close()
                self.assertTrue(s.find("UserWarning: I'm warning you...\n") > 0)

                #See if an explicit file uses the original implementation
                file = cStringIO.StringIO()
                warnings.showwarning("Explicit", UserWarning, "dummy.py", 42,
                                        file, "Dummy line")
                s = file.getvalue()
                file.close()
                self.assertEqual(s,
                        "dummy.py:42: UserWarning: Explicit\n  Dummy line\n")
            finally:
                logging.captureWarnings(False) 
Example 17
Project: bazarr   Author: morpheus65535   File: __main__.py    License: GNU General Public License v3.0 6 votes vote down vote up
def run():  # pragma: no cover
    """Run Markdown from the command line."""

    # Parse options and adjust logging level if necessary
    options, logging_level = parse_options()
    if not options:
        sys.exit(2)
    logger.setLevel(logging_level)
    console_handler = logging.StreamHandler()
    logger.addHandler(console_handler)
    if logging_level <= WARNING:
        # Ensure deprecation warnings get displayed
        warnings.filterwarnings('default')
        logging.captureWarnings(True)
        warn_logger = logging.getLogger('py.warnings')
        warn_logger.addHandler(console_handler)

    # Run
    markdown.markdownFromFile(**options) 
Example 18
Project: xtgeo   Author: equinor   File: xtgeo_dialog.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def basiclogger(self, name, logginglevel=None, loggingformat=None, info=False):
        """Initiate the logger by some default settings."""

        if logginglevel is not None and self._logginglevel_fromenv is None:
            self.logginglevel = logginglevel

        if loggingformat is not None and isinstance(loggingformat, int):
            self._lformatlevel = loggingformat

        logging.basicConfig(stream=sys.stdout)
        fmt = self.loggingformat
        self._loggingname = name
        if info:
            print(
                "Logginglevel is {}, formatlevel is {}, and format is {}".format(
                    self.logginglevel, self._lformatlevel, fmt
                )
            )
        self._rootlogger.setLevel(self.numericallogginglevel)

        logging.captureWarnings(True)

        return logging.getLogger(self._loggingname) 
Example 19
Project: evtools   Author: the-mace   File: tl_tweets.py    License: MIT License 6 votes vote down vote up
def tweet_search(log, item, limit=50):
    log.debug("   Searching twitter for %s", item)
    check_twitter_config()
    if len(item) > 500:
        log.error("      Search string too long")
        raise Exception("Search string too long: %d", len(item))
    logging.captureWarnings(True)
    old_level = log.getEffectiveLevel()
    log.setLevel(logging.ERROR)
    twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
    try:
        result = twitter.search(q=item, count=limit)
    except TwythonAuthError as e:
        twitter_auth_issue(e)
        raise
    except:
        raise
    log.setLevel(old_level)
    return result 
Example 20
Project: evtools   Author: the-mace   File: tl_tweets.py    License: MIT License 6 votes vote down vote up
def check_relationship(log, id):
    my_screen_name = get_screen_name(log)
    if my_screen_name == "Unknown":
        raise("Couldn't get my own screen name")
    log.debug("      Checking relationship of %s with me (%s)", id, my_screen_name)
    check_twitter_config()
    logging.captureWarnings(True)
    old_level = log.getEffectiveLevel()
    log.setLevel(logging.ERROR)
    twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
    try:
        result = twitter.show_friendship(source_screen_name=my_screen_name, target_screen_name=id)
    except TwythonAuthError as e:
        log.setLevel(old_level)
        log.exception("   Problem trying to check relationship")
        twitter_auth_issue(e)
        raise
    except:
        raise
    log.setLevel(old_level)
    return result["relationship"]["source"]["following"], result["relationship"]["source"]["followed_by"] 
Example 21
Project: evtools   Author: the-mace   File: tl_tweets.py    License: MIT License 6 votes vote down vote up
def follow_twitter_user(log, id):
    log.debug("   Following %s", id)
    check_twitter_config()
    logging.captureWarnings(True)
    old_level = log.getEffectiveLevel()
    log.setLevel(logging.ERROR)
    twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
    try:
        twitter.create_friendship(screen_name=id)
    except TwythonAuthError as e:
        log.setLevel(old_level)
        log.exception("   Problem trying to follow twitter user")
        twitter_auth_issue(e)
        raise
    except:
        raise
    log.setLevel(old_level) 
Example 22
Project: evtools   Author: the-mace   File: tl_tweets.py    License: MIT License 6 votes vote down vote up
def unfollow_twitter_user(log, id):
    log.debug("   Unfollowing %s", id)
    check_twitter_config()
    logging.captureWarnings(True)
    old_level = log.getEffectiveLevel()
    log.setLevel(logging.ERROR)
    twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
    try:
        twitter.destroy_friendship(screen_name=id)
    except TwythonAuthError as e:
        log.setLevel(old_level)
        log.exception("Error unfollowing %s", id)
        twitter_auth_issue(e)
        raise
    except:
        log.exception("Error unfollowing %s", id)
    log.setLevel(old_level) 
Example 23
Project: evtools   Author: the-mace   File: tl_tweets.py    License: MIT License 6 votes vote down vote up
def get_screen_name(log):
    global MYSELF
    if not MYSELF or MYSELF == "Unknown":
        log.debug("   Getting current user screen name")
        check_twitter_config()
        logging.captureWarnings(True)
        old_level = log.getEffectiveLevel()
        log.setLevel(logging.ERROR)
        twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
        try:
            details = twitter.verify_credentials()
        except TwythonAuthError as e:
            log.setLevel(old_level)
            log.exception("   Problem trying to get screen name")
            twitter_auth_issue(e)
            raise
        except:
            log.exception("   Problem trying to get screen name")
            details = None
        log.setLevel(old_level)
        name = "Unknown"
        if details:
            name = details["screen_name"]
        MYSELF = name
    return MYSELF 
Example 24
Project: qutebrowser   Author: qutebrowser   File: test_log.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_ignore_py_warnings(caplog):
    logging.captureWarnings(True)
    with log.ignore_py_warnings(category=UserWarning):
        warnings.warn("hidden", UserWarning)
    with caplog.at_level(logging.WARNING):
        warnings.warn("not hidden", UserWarning)
    assert len(caplog.records) == 1
    msg = caplog.messages[0].splitlines()[0]
    assert msg.endswith("UserWarning: not hidden") 
Example 25
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 26
Project: stdpopsim   Author: popsim-consortium   File: cli.py    License: GNU General Public License v3.0 5 votes vote down vote up
def setup_logging(args):
    log_level = "ERROR"
    if args.verbose == 1:
        log_level = "WARN"
    elif args.verbose == 2:
        log_level = "INFO"
    elif args.verbose > 2:
        log_level = "DEBUG"
    handler = logging.StreamHandler(sys.stderr)
    handler.setFormatter(CLIFormatter())
    logging.basicConfig(handlers=[handler], level=log_level)
    logging.captureWarnings(True) 
Example 27
Project: king-phisher   Author: rsmusllp   File: utilities.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def configure_stream_logger(logger, level=None):
	"""
	Configure the default stream handler for logging messages to the console.
	This also configures the basic logging environment for the application.

	:param str logger: The logger to add the stream handler for.
	:param level: The level to set the logger to, will default to WARNING if no level is specified.
	:type level: None, int, str
	:return: The new configured stream handler.
	:rtype: :py:class:`logging.StreamHandler`
	"""
	if level is None:
		level = constants.DEFAULT_LOG_LEVEL
	if isinstance(level, str):
		level = getattr(logging, level)
	root_logger = logging.getLogger('')
	for handler in root_logger.handlers:
		root_logger.removeHandler(handler)

	logging.getLogger(logger).setLevel(logging.DEBUG)
	console_log_handler = logging.StreamHandler()
	console_log_handler.setLevel(level)
	if its.on_linux:
		console_log_handler.setFormatter(color.ColoredLogFormatter('%(levelname)s %(message)s'))
	else:
		console_log_handler.setFormatter(logging.Formatter('%(levelname)-8s %(message)s'))
	logging.getLogger(logger).addHandler(console_log_handler)
	logging.captureWarnings(True)
	return console_log_handler 
Example 28
Project: rasa_wechat   Author: Rowl1ng   File: server.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, model_directory, nlu_model, verbose, log_file):
        logging.basicConfig(filename=log_file,
                            level="DEBUG" if verbose else "INFO")
        logging.captureWarnings(True)

        self.agent = self._create_agent(model_directory, nlu_model) 
Example 29
Project: courseraprogramming   Author: coursera   File: main.py    License: Apache License 2.0 5 votes vote down vote up
def main():
    "Boots up the command line tool"
    logging.captureWarnings(True)
    args = build_parser().parse_args()
    # Configure logging
    args.setup_logging(args)
    # Dispatch into the appropriate subcommand function.

    try:
        return args.func(args)
    except SystemExit:
        raise
    except:
        logging.exception('Problem when running command. Sorry!')
        sys.exit(1) 
Example 30
Project: atomic-reactor   Author: containerbuildsystem   File: main.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def run(self):
        self.set_arguments()
        args = self.parser.parse_args()
        logging.captureWarnings(True)

        if args.verbose:
            set_logging(level=logging.DEBUG)
            set_logging_osbs(level=logging.DEBUG)
        elif args.quiet:
            set_logging(level=logging.WARNING)
            set_logging_osbs(level=logging.WARNING)
        else:
            set_logging(level=logging.INFO)
            set_logging_osbs(level=logging.INFO)
        try:
            args.func(args)
        except AttributeError:
            if hasattr(args, 'func'):
                raise
            else:
                self.parser.print_help()
        except KeyboardInterrupt:
            pass
        except Exception as ex:
            if args.verbose:
                raise
            else:
                logger.error("exception caught: %s", exception_message(ex))