当前位置: 首页>>代码示例>>Python>>正文


Python logging.captureWarnings方法代码示例

本文整理汇总了Python中logging.captureWarnings方法的典型用法代码示例。如果您正苦于以下问题:Python logging.captureWarnings方法的具体用法?Python logging.captureWarnings怎么用?Python logging.captureWarnings使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在logging的用法示例。


在下文中一共展示了logging.captureWarnings方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: capture

# 需要导入模块: import logging [as 别名]
# 或者: from logging import captureWarnings [as 别名]
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) 
开发者ID:AdamGagorik,项目名称:pydarkstar,代码行数:22,代码来源:logutils.py

示例2: configure_logging

# 需要导入模块: import logging [as 别名]
# 或者: from logging import captureWarnings [as 别名]
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) 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:19,代码来源:log.py

示例3: test_warnings

# 需要导入模块: import logging [as 别名]
# 或者: from logging import captureWarnings [as 别名]
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) 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:27,代码来源:test_logging.py

示例4: run

# 需要导入模块: import logging [as 别名]
# 或者: from logging import captureWarnings [as 别名]
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) 
开发者ID:reBiocoder,项目名称:bioforum,代码行数:21,代码来源:__main__.py

示例5: test_warnings

# 需要导入模块: import logging [as 别名]
# 或者: from logging import captureWarnings [as 别名]
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") 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:25,代码来源:test_logging.py

示例6: _init_logger

# 需要导入模块: import logging [as 别名]
# 或者: from logging import captureWarnings [as 别名]
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") 
开发者ID:PyCQA,项目名称:bandit,代码行数:23,代码来源:main.py

示例7: post_configure_actor_logging

# 需要导入模块: import logging [as 别名]
# 或者: from logging import captureWarnings [as 别名]
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"]) 
开发者ID:elastic,项目名称:rally,代码行数:21,代码来源:log.py

示例8: configure_logging

# 需要导入模块: import logging [as 别名]
# 或者: from logging import captureWarnings [as 别名]
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) 
开发者ID:drexly,项目名称:openhgsenti,代码行数:19,代码来源:log.py

示例9: __initialize_log

# 需要导入模块: import logging [as 别名]
# 或者: from logging import captureWarnings [as 别名]
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__) 
开发者ID:cstoeckert,项目名称:iterativeWGCNA,代码行数:18,代码来源:iterativeWGCNA.py

示例10: setup_logger

# 需要导入模块: import logging [as 别名]
# 或者: from logging import captureWarnings [as 别名]
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 
开发者ID:crowsonkb,项目名称:style_transfer,代码行数:18,代码来源:log_utils.py

示例11: basiclogger

# 需要导入模块: import logging [as 别名]
# 或者: from logging import captureWarnings [as 别名]
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) 
开发者ID:equinor,项目名称:xtgeo,代码行数:25,代码来源:xtgeo_dialog.py

示例12: tweet_search

# 需要导入模块: import logging [as 别名]
# 或者: from logging import captureWarnings [as 别名]
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 
开发者ID:the-mace,项目名称:evtools,代码行数:21,代码来源:tl_tweets.py

示例13: check_relationship

# 需要导入模块: import logging [as 别名]
# 或者: from logging import captureWarnings [as 别名]
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"] 
开发者ID:the-mace,项目名称:evtools,代码行数:23,代码来源:tl_tweets.py

示例14: follow_twitter_user

# 需要导入模块: import logging [as 别名]
# 或者: from logging import captureWarnings [as 别名]
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) 
开发者ID:the-mace,项目名称:evtools,代码行数:19,代码来源:tl_tweets.py

示例15: unfollow_twitter_user

# 需要导入模块: import logging [as 别名]
# 或者: from logging import captureWarnings [as 别名]
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) 
开发者ID:the-mace,项目名称:evtools,代码行数:19,代码来源:tl_tweets.py


注:本文中的logging.captureWarnings方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。