本文整理汇总了Python中loguru.logger.error方法的典型用法代码示例。如果您正苦于以下问题:Python logger.error方法的具体用法?Python logger.error怎么用?Python logger.error使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类loguru.logger
的用法示例。
在下文中一共展示了logger.error方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: write
# 需要导入模块: from loguru import logger [as 别名]
# 或者: from loguru.logger import error [as 别名]
def write(self,msg,level='info'):
"Write out a message"
fname = inspect.stack()[2][3] #May be use a entry-exit decorator instead
d = {'caller_func': fname}
if level.lower()== 'debug':
logger.debug("{module} | {msg}",module=d['caller_func'],msg=msg)
elif level.lower()== 'info':
logger.info("{module} | {msg}",module=d['caller_func'],msg=msg)
elif level.lower()== 'warn' or level.lower()=='warning':
logger.warning("{module} | {msg}",module=d['caller_func'],msg=msg)
elif level.lower()== 'error':
logger.error("{module} | {msg}",module=d['caller_func'],msg=msg)
elif level.lower()== 'critical':
logger.critical("{module} | {msg}",module=d['caller_func'],msg=msg)
else:
logger.critical("Unknown level passed for the msg: {}", msg)
示例2: add
# 需要导入模块: from loguru import logger [as 别名]
# 或者: from loguru.logger import error [as 别名]
def add(self, lifeform: Lifeform, loc: Tuple[int, int]):
"""Add a lifeform to the board
Parameters
----------
lifeform: :obj:`seagull.lifeforms.base.Lifeform`
A lifeform that can evolve in the board
loc : array_like of size 2
Initial location of the lifeform on the board
"""
try:
row, col = loc
height, width = lifeform.size
self.state[row : row + height, col : col + width] = lifeform.layout
except ValueError:
logger.error("Lifeform is out-of-bounds!")
raise
示例3: __ensure_absolute
# 需要导入模块: from loguru import logger [as 别名]
# 或者: from loguru.logger import error [as 别名]
def __ensure_absolute(path: Text) -> Text:
if path.startswith("./"):
# Linux/Darwin, hrun ./test.yml
path = path[len("./") :]
elif path.startswith(".\\"):
# Windows, hrun .\\test.yml
path = path[len(".\\") :]
path = ensure_path_sep(path)
project_meta = load_project_meta(path)
if os.path.isabs(path):
absolute_path = path
else:
absolute_path = os.path.join(project_meta.RootDir, path)
if not os.path.isfile(absolute_path):
logger.error(f"Invalid testcase file path: {absolute_path}")
sys.exit(1)
return absolute_path
示例4: format_pytest_with_black
# 需要导入模块: from loguru import logger [as 别名]
# 或者: from loguru.logger import error [as 别名]
def format_pytest_with_black(*python_paths: Text) -> NoReturn:
logger.info("format pytest cases with black ...")
try:
if is_support_multiprocessing() or len(python_paths) <= 1:
subprocess.run(["black", *python_paths])
else:
logger.warning(
f"this system does not support multiprocessing well, format files one by one ..."
)
[subprocess.run(["black", path]) for path in python_paths]
except subprocess.CalledProcessError as ex:
capture_exception(ex)
logger.error(ex)
sys.exit(1)
except FileNotFoundError:
err_msg = """
missing dependency tool: black
install black manually and try again:
$ pip install black
"""
logger.error(err_msg)
sys.exit(1)
示例5: main_make
# 需要导入模块: from loguru import logger [as 别名]
# 或者: from loguru.logger import error [as 别名]
def main_make(tests_paths: List[Text]) -> List[Text]:
if not tests_paths:
return []
for tests_path in tests_paths:
tests_path = ensure_path_sep(tests_path)
if not os.path.isabs(tests_path):
tests_path = os.path.join(os.getcwd(), tests_path)
try:
__make(tests_path)
except exceptions.MyBaseError as ex:
logger.error(ex)
sys.exit(1)
# format pytest files
pytest_files_format_list = pytest_files_made_cache_mapping.keys()
format_pytest_with_black(*pytest_files_format_list)
return list(pytest_files_run_set)
示例6: debug_python
# 需要导入模块: from loguru import logger [as 别名]
# 或者: from loguru.logger import error [as 别名]
def debug_python(request: Request):
body = await request.body()
if request.headers.get("content-transfer-encoding") == "base64":
# TODO: decode base64
pass
resp = {"code": 0, "message": "success", "result": ""}
try:
with stdout_io() as s:
exec(body, globals())
output = s.getvalue()
resp["result"] = output
except Exception as ex:
resp["code"] = 1
resp["message"] = "fail"
resp["result"] = str(ex)
logger.error(resp)
return resp
示例7: __getattr__
# 需要导入模块: from loguru import logger [as 别名]
# 或者: from loguru.logger import error [as 别名]
def __getattr__(self, key):
if key in ["json", "content", "body"]:
try:
value = self.resp_obj.json()
except ValueError:
value = self.resp_obj.content
elif key == "cookies":
value = self.resp_obj.cookies.get_dict()
else:
try:
value = getattr(self.resp_obj, key)
except AttributeError:
err_msg = "ResponseObject does not have attribute: {}".format(key)
logger.error(err_msg)
raise exceptions.ParamsError(err_msg)
self.__dict__[key] = value
return value
示例8: load_debugtalk_functions
# 需要导入模块: from loguru import logger [as 别名]
# 或者: from loguru.logger import error [as 别名]
def load_debugtalk_functions() -> Dict[Text, Callable]:
""" load project debugtalk.py module functions
debugtalk.py should be located in project root directory.
Returns:
dict: debugtalk module functions mapping
{
"func1_name": func1,
"func2_name": func2
}
"""
# load debugtalk.py module
try:
imported_module = importlib.import_module("debugtalk")
except Exception as ex:
logger.error(f"error occurred in debugtalk.py: {ex}")
sys.exit(1)
# reload to refresh previously loaded module
imported_module = importlib.reload(imported_module)
return load_module_functions(imported_module)
示例9: main
# 需要导入模块: from loguru import logger [as 别名]
# 或者: from loguru.logger import error [as 别名]
def main():
logger.info("Wait for RedisDB...")
try:
await wait_redis()
except tenacity.RetryError:
logger.error("Failed to establish connection with RedisDB.")
exit(1)
logger.info("Wait for PostgreSQL...")
try:
await wait_postgres()
except tenacity.RetryError:
logger.error("Failed to establish connection with PostgreSQL.")
exit(1)
logger.info("Ready.")
示例10: create_super_user
# 需要导入模块: from loguru import logger [as 别名]
# 或者: from loguru.logger import error [as 别名]
def create_super_user(user_id: int, remove: bool) -> bool:
user = await User.query.where(User.id == user_id).gino.first()
if not user:
logger.error("User is not registered in bot")
raise ValueError("User is not registered in bot")
logger.info(
"Loaded user {user}. It's registered at {register_date}.",
user=user.id,
register_date=user.created_at,
)
await user.update(is_superuser=not remove).apply()
if remove:
logger.warning("User {user} now IS NOT superuser", user=user_id)
else:
logger.warning("User {user} now IS superuser", user=user_id)
return True
示例11: get_logged_in_athlete
# 需要导入模块: from loguru import logger [as 别名]
# 或者: from loguru.logger import error [as 别名]
def get_logged_in_athlete(self):
"""Get logged in athlete
Returns
-------
athlete: Athlete object
"""
try:
rv = Athlete(self.athletes_api.get_logged_in_athlete())
except ApiException as e:
logger.error(f""""
Error in strava_swagger_client.AthletesApi!
STRAVA_ACCESS_TOKEN is likely out of date!
Check the https://github.com/sladkovm/strava-oauth for help.
Returning None.
Original Error:
{e}""")
rv = None
return rv
示例12: main
# 需要导入模块: from loguru import logger [as 别名]
# 或者: from loguru.logger import error [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:")
示例13: res_or_raise
# 需要导入模块: from loguru import logger [as 别名]
# 或者: from loguru.logger import error [as 别名]
def res_or_raise(response: dict) -> CALL_RETURN_TYPE:
"""
Return the result of the response, or raise an error with code and message.
Parameters:
response: a response sent by the server.
Returns:
The "result" value of the response.
Raises:
ClientException: when the response contains an error (client/server error).
See the [`ClientException`][aria2p.client.ClientException] class.
"""
if "error" in response:
raise Client.response_as_exception(response)
return response["result"]
示例14: test_exception_formatting
# 需要导入模块: from loguru import logger [as 别名]
# 或者: from loguru.logger import error [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
示例15: test_onerror
# 需要导入模块: from loguru import logger [as 别名]
# 或者: from loguru.logger import error [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"
)