本文整理汇总了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)
示例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)
示例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)
示例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)
示例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")
示例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")
示例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"])
示例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)
示例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__)
示例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
示例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)
示例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
示例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"]
示例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)
示例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)