本文整理匯總了Python中loguru.logger.exception方法的典型用法代碼示例。如果您正苦於以下問題:Python logger.exception方法的具體用法?Python logger.exception怎麽用?Python logger.exception使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類loguru.logger
的用法示例。
在下文中一共展示了logger.exception方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: resume
# 需要導入模塊: from loguru import logger [as 別名]
# 或者: from loguru.logger import exception [as 別名]
def resume(self, downloads: List[Download]) -> List[bool]:
"""
Resume (unpause) the given downloads.
Parameters:
downloads: the list of downloads to resume.
Returns:
Success or failure of the operation for each given download.
"""
# TODO: batch/multicall candidate
result = []
for download in downloads:
try:
self.client.unpause(download.gid)
except ClientException as error:
logger.debug(f"Failed to resume download {download.gid}")
logger.opt(exception=True).trace(error)
result.append(error)
else:
result.append(True)
return result
示例2: main
# 需要導入模塊: from loguru import logger [as 別名]
# 或者: from loguru.logger import exception [as 別名]
def main() -> None:
parser = get_argument_parser()
arguments = parser.parse_args()
logger.stop(0)
logger.add(sys.stderr, level=arguments.logging_level)
# noinspection PyBroadException
try:
cli_main(arguments)
except KeyboardInterrupt:
logger.info("Aborted")
except ConfigError as error:
logger.error("Invalid configuration: {}", error)
except MissingDependencyError as error:
logger.error("Missing dependency: {}", error)
except Exception:
logger.exception("Unexpected error occurred:")
示例3: test_exception
# 需要導入模塊: from loguru import logger [as 別名]
# 或者: from loguru.logger import exception [as 別名]
def test_exception(make_logging_logger, capsys, use_opt):
make_logging_logger("tests", StreamHandler(sys.stderr))
logger.add(PropagateHandler(), format="{message}")
try:
1 / 0
except:
if use_opt:
logger.opt(exception=True).error("Oops...")
else:
logger.exception("Oops...")
out, err = capsys.readouterr()
lines = err.strip().splitlines()
error = "ZeroDivisionError: division by zero"
assert out == ""
assert lines[0] == "Oops..."
assert lines[-1] == error
assert err.count(error) == 1
示例4: test_enqueue_with_exception
# 需要導入模塊: from loguru import logger [as 別名]
# 或者: from loguru.logger import exception [as 別名]
def test_enqueue_with_exception():
x = []
def sink(message):
time.sleep(0.1)
x.append(message)
logger.add(sink, format="{message}", enqueue=True)
try:
1 / 0
except ZeroDivisionError:
logger.exception("Error")
assert len(x) == 0
time.sleep(0.2)
assert len(x) == 1
lines = x[0].splitlines()
assert lines[0] == "Error"
assert lines[-1] == "ZeroDivisionError: division by zero"
示例5: test_no_exception
# 需要導入模塊: from loguru import logger [as 別名]
# 或者: from loguru.logger import exception [as 別名]
def test_no_exception():
result = None
class NoExceptionHandler(Handler):
def emit(self, record):
nonlocal result
result = bool(not record.exc_info)
logger.add(NoExceptionHandler())
try:
1 / 0
except ZeroDivisionError:
logger.exception("Error")
assert result is False
示例6: test_exception
# 需要導入模塊: from loguru import logger [as 別名]
# 或者: from loguru.logger import exception [as 別名]
def test_exception(capsys):
result = None
class ExceptionHandler(Handler):
def emit(self, record):
nonlocal result
result = bool(record.exc_info)
logger.add(ExceptionHandler())
try:
1 / 0
except ZeroDivisionError:
logger.exception("Error")
assert result is True
示例7: test_exception_formatting
# 需要導入模塊: from loguru import logger [as 別名]
# 或者: from loguru.logger import exception [as 別名]
def test_exception_formatting(tmpdir):
file = tmpdir.join("test.log")
logger.add(FileHandler(str(file)), format="{message}")
try:
1 / 0
except ZeroDivisionError:
logger.exception("Error")
result = file.read()
lines = result.strip().splitlines()
error = "ZeroDivisionError: division by zero"
assert lines[1].startswith("Traceback")
assert lines[-1] == error
assert result.count(error) == 1
示例8: test_diagnose
# 需要導入模塊: from loguru import logger [as 別名]
# 或者: from loguru.logger import exception [as 別名]
def test_diagnose(writer):
logger.add(writer, format="{message}", diagnose=True)
try:
1 / 0
except:
logger.exception("")
result_with = writer.read().strip()
logger.remove()
writer.clear()
logger.add(writer, format="{message}", diagnose=False)
try:
1 / 0
except:
logger.exception("")
result_without = writer.read().strip()
assert len(result_with.splitlines()) > len(result_without.splitlines())
示例9: test_sink_encoding
# 需要導入模塊: from loguru import logger [as 別名]
# 或者: from loguru.logger import exception [as 別名]
def test_sink_encoding(writer, encoding):
class Writer:
def __init__(self, encoding):
self.encoding = encoding
self.output = ""
def write(self, message):
self.output += message
writer = Writer(encoding)
logger.add(writer, backtrace=True, diagnose=True, colorize=False, format="", catch=False)
def foo(a, b):
a / b
def bar(c):
foo(c, 0)
try:
bar(4)
except ZeroDivisionError:
logger.exception("")
assert writer.output.endswith("ZeroDivisionError: division by zero\n")
示例10: test_onerror
# 需要導入模塊: from loguru import logger [as 別名]
# 或者: from loguru.logger import exception [as 別名]
def test_onerror(writer):
is_error_valid = False
logger.add(writer, format="{message}")
def onerror(error):
nonlocal is_error_valid
logger.info("Called after logged message")
_, exception, _ = sys.exc_info()
is_error_valid = (error == exception) and isinstance(error, ZeroDivisionError)
@logger.catch(onerror=onerror)
def a():
1 / 0
a()
assert is_error_valid
assert writer.read().endswith(
"ZeroDivisionError: division by zero\n" "Called after logged message\n"
)
示例11: _render
# 需要導入模塊: from loguru import logger [as 別名]
# 或者: from loguru.logger import exception [as 別名]
def _render(self, element: AbstractElement) -> LayoutUpdate:
# current element ids
current: Set[str] = set(self._element_state)
# all element updates
new: Dict[str, Dict[str, Any]] = {}
parent = self._element_parent(element)
render_error: Optional[Exception] = None
try:
async for element_id, model in self._render_element(element, parent):
new[element_id] = model
except asyncio.CancelledError:
raise # we don't want to supress cancellations
except Exception as error:
logger.exception(f"Failed to render {element}")
render_error = error
finally:
# all deleted element ids
old: List[str] = list(current.difference(self._element_state))
update = LayoutUpdate(element.id, new, old, render_error)
# render bundle
return update
示例12: run_once
# 需要導入模塊: from loguru import logger [as 別名]
# 或者: from loguru.logger import exception [as 別名]
def run_once(self):
"""Run each source once, passing artifacts to each operator."""
# Track some statistics about artifacts in a summary object.
summary = collections.Counter()
for source in self.sources:
# Run the source to collect artifacts.
logger.debug(f"Running source '{source}'")
try:
with self.statsd.timer(f'source.{source}'):
saved_state, artifacts = self.sources[source].run(self.statedb.get_state(source))
except Exception:
self.statsd.incr(f'error.source.{source}')
logger.exception(f"Unknown error in source '{source}'")
continue
# Save the source state.
self.statedb.save_state(source, saved_state)
# Process artifacts with each operator.
for operator in self.operators:
logger.debug(f"Processing {len(artifacts)} artifacts from source '{source}' with operator '{operator}'")
try:
with self.statsd.timer(f'operator.{operator}'):
self.operators[operator].process(artifacts)
except Exception:
self.statsd.incr(f'error.operator.{operator}')
logger.exception(f"Unknown error in operator '{operator}'")
continue
# Record stats and update the summary.
types = artifact_types(artifacts)
summary.update(types)
for artifact_type in types:
self.statsd.incr(f'source.{source}.{artifact_type}', types[artifact_type])
self.statsd.incr(f'artifacts.{artifact_type}', types[artifact_type])
# Log the summary.
logger.log('NOTIFY', f"New artifacts: {dict(summary)}")
示例13: __make_request_method
# 需要導入模塊: from loguru import logger [as 別名]
# 或者: from loguru.logger import exception [as 別名]
def __make_request_method(self, teststep_dict, entry_json):
""" parse HAR entry request method, and make teststep method.
"""
method = entry_json["request"].get("method")
if not method:
logger.exception("method missed in request.")
sys.exit(1)
teststep_dict["request"]["method"] = method
示例14: superuser
# 需要導入模塊: from loguru import logger [as 別名]
# 或者: from loguru.logger import exception [as 別名]
def superuser(user_id: int, remove: bool):
from app.utils.executor import runner
from app.utils.superuser import create_super_user
try:
result = runner.start(create_super_user(user_id, remove))
except Exception as e:
logger.exception("Failed to create superuser: {e}", e=e)
result = None
if not result:
exit(1)
示例15: errors_handler
# 需要導入模塊: from loguru import logger [as 別名]
# 或者: from loguru.logger import exception [as 別名]
def errors_handler(update: types.Update, exception: Exception):
try:
raise exception
except Exception as e:
logger.exception("Cause exception {e} in update {update}", e=e, update=update)
return True