當前位置: 首頁>>代碼示例>>Python>>正文


Python logger.error方法代碼示例

本文整理匯總了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) 
開發者ID:qxf2,項目名稱:makemework,代碼行數:18,代碼來源:Base_Logging.py

示例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 
開發者ID:ljvmiranda921,項目名稱:seagull,代碼行數:19,代碼來源:board.py

示例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 
開發者ID:httprunner,項目名稱:httprunner,代碼行數:23,代碼來源:make.py

示例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) 
開發者ID:httprunner,項目名稱:httprunner,代碼行數:24,代碼來源:make.py

示例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) 
開發者ID:httprunner,項目名稱:httprunner,代碼行數:22,代碼來源:make.py

示例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 
開發者ID:httprunner,項目名稱:httprunner,代碼行數:22,代碼來源:debugtalk.py

示例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 
開發者ID:httprunner,項目名稱:httprunner,代碼行數:20,代碼來源:response.py

示例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) 
開發者ID:httprunner,項目名稱:httprunner,代碼行數:24,代碼來源:loader.py

示例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.") 
開發者ID:aiogram,項目名稱:bot,代碼行數:18,代碼來源:before_start.py

示例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 
開發者ID:aiogram,項目名稱:bot,代碼行數:19,代碼來源:superuser.py

示例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 
開發者ID:sladkovm,項目名稱:stravaio,代碼行數:22,代碼來源:stravaio.py

示例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:") 
開發者ID:cryzed,項目名稱:TrafficToll,代碼行數:19,代碼來源:__main__.py

示例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"] 
開發者ID:pawamoy,項目名稱:aria2p,代碼行數:19,代碼來源:client.py

示例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 
開發者ID:Delgan,項目名稱:loguru,代碼行數:19,代碼來源:test_standard_handler.py

示例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"
    ) 
開發者ID:Delgan,項目名稱:loguru,代碼行數:22,代碼來源:test_catch_exceptions.py


注:本文中的loguru.logger.error方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。