1
0
mirror of https://github.com/checktheroads/hyperglass synced 2024-05-11 05:55:08 +00:00

fix exception printing

This commit is contained in:
checktheroads
2020-10-17 08:51:19 -07:00
parent 907e6e0818
commit d64520727a
5 changed files with 45 additions and 73 deletions

View File

@@ -5,6 +5,12 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## 1.0.0-beta62 - 2020-10-17
### Fixed
- Fix an issue causing exceptions not to be logged to the log file (but logged to stdout).
## 1.0.0-beta61 - 2020-10-11 ## 1.0.0-beta61 - 2020-10-11
### POTENTIALLY BREAKING CHANGE ### POTENTIALLY BREAKING CHANGE

View File

@@ -41,16 +41,12 @@ import logging
# Third Party # Third Party
import uvloop import uvloop
import rich.traceback
# Project # Project
from hyperglass.log import _get_rich from hyperglass.log import _get_rich
from hyperglass.util import set_app_path from hyperglass.util import set_app_path
from hyperglass.constants import METADATA from hyperglass.constants import METADATA
# Use Rich for traceback formatting.
rich.traceback.install()
# Set Rich as the default logging handler. # Set Rich as the default logging handler.
logging.getLogger().handlers = [_get_rich(True)] logging.getLogger().handlers = [_get_rich(True)]

View File

@@ -4,7 +4,7 @@
from datetime import datetime from datetime import datetime
__name__ = "hyperglass" __name__ = "hyperglass"
__version__ = "1.0.0-beta.61" __version__ = "1.0.0-beta.62"
__author__ = "Matt Love" __author__ = "Matt Love"
__copyright__ = f"Copyright {datetime.now().year} Matthew Love" __copyright__ = f"Copyright {datetime.now().year} Matthew Love"
__license__ = "BSD 3-Clause Clear License" __license__ = "BSD 3-Clause Clear License"

View File

@@ -2,12 +2,17 @@
# Standard Library # Standard Library
import json as _json import json as _json
from typing import Dict, List, Union, Sequence from typing import Dict, List, Union, Optional, Sequence
# Third Party
from rich.console import Console
# Project # Project
from hyperglass.log import log from hyperglass.log import log
from hyperglass.constants import STATUS_CODE_MAP from hyperglass.constants import STATUS_CODE_MAP
console = Console()
def validation_error_message(*errors: Dict) -> str: def validation_error_message(*errors: Dict) -> str:
"""Parse errors return from pydantic.ValidationError.errors().""" """Parse errors return from pydantic.ValidationError.errors()."""
@@ -24,14 +29,13 @@ def validation_error_message(*errors: Dict) -> str:
class HyperglassError(Exception): class HyperglassError(Exception):
"""hyperglass base exception.""" """hyperglass base exception."""
def __init__(self, message="", level="warning", keywords=None): def __init__(
"""Initialize the hyperglass base exception class. self,
message: str = "",
Keyword Arguments: level: str = "warning",
message {str} -- Error message (default: {""}) keywords: Optional[List[str]] = None,
level {str} -- Error severity (default: {"warning"}) ) -> None:
keywords {list} -- 'Important' keywords (default: {None}) """Initialize the hyperglass base exception class."""
"""
self._message = message self._message = message
self._level = level self._level = level
self._keywords = keywords or [] self._keywords = keywords or []
@@ -42,76 +46,46 @@ class HyperglassError(Exception):
else: else:
log.info(repr(self)) log.info(repr(self))
def __str__(self): console.print_exception(extra_lines=6)
"""Return the instance's error message.
Returns: def __str__(self) -> str:
{str} -- Error Message """Return the instance's error message."""
"""
return self._message return self._message
def __repr__(self): def __repr__(self) -> str:
"""Return the instance's severity & error message in a string. """Return the instance's severity & error message in a string."""
Returns:
{str} -- Error message with code
"""
return f"[{self.level.upper()}] {self._message}" return f"[{self.level.upper()}] {self._message}"
def dict(self): def dict(self) -> Dict:
"""Return the instance's attributes as a dictionary. """Return the instance's attributes as a dictionary."""
Returns:
{dict} -- Exception attributes in dict
"""
return { return {
"message": self._message, "message": self._message,
"level": self._level, "level": self._level,
"keywords": self._keywords, "keywords": self._keywords,
} }
def json(self): def json(self) -> str:
"""Return the instance's attributes as a JSON object. """Return the instance's attributes as a JSON object."""
Returns:
{str} -- Exception attributes as JSON
"""
return _json.dumps(self.__dict__()) return _json.dumps(self.__dict__())
@property @property
def message(self): def message(self) -> str:
"""Return the instance's `message` attribute. """Return the instance's `message` attribute."""
Returns:
{str} -- Error Message
"""
return self._message return self._message
@property @property
def level(self): def level(self) -> str:
"""Return the instance's `level` attribute. """Return the instance's `level` attribute."""
Returns:
{str} -- Alert name
"""
return self._level return self._level
@property @property
def keywords(self): def keywords(self) -> List[str]:
"""Return the instance's `keywords` attribute. """Return the instance's `keywords` attribute."""
Returns:
{list} -- Keywords List
"""
return self._keywords return self._keywords
@property @property
def status_code(self): def status_code(self) -> int:
"""Return HTTP status code based on level level. """Return HTTP status code based on level level."""
Returns:
{int} -- HTTP Status Code
"""
return STATUS_CODE_MAP.get(self._level, 500) return STATUS_CODE_MAP.get(self._level, 500)
@@ -120,14 +94,10 @@ class _UnformattedHyperglassError(HyperglassError):
_level = "warning" _level = "warning"
def __init__(self, unformatted_msg="", level=None, **kwargs): def __init__(
"""Format error message with keyword arguments. self, unformatted_msg: str = "", level: Optional[str] = None, **kwargs
) -> None:
Keyword Arguments: """Format error message with keyword arguments."""
message {str} -- Error message (default: {""})
level {str} -- Error severity (default: {"warning"})
keywords {list} -- 'Important' keywords (default: {None})
"""
self._message = unformatted_msg.format(**kwargs) self._message = unformatted_msg.format(**kwargs)
self._level = level or self._level self._level = level or self._level
self._keywords = list(kwargs.values()) self._keywords = list(kwargs.values())
@@ -140,7 +110,7 @@ class _PredefinedHyperglassError(HyperglassError):
_message = "undefined" _message = "undefined"
_level = "warning" _level = "warning"
def __init__(self, level=None, **kwargs): def __init__(self, level: Optional[str] = None, **kwargs) -> None:
self._fmt_msg = self._message.format(**kwargs) self._fmt_msg = self._message.format(**kwargs)
self._level = level or self._level self._level = level or self._level
self._keywords = list(kwargs.values()) self._keywords = list(kwargs.values())
@@ -152,7 +122,7 @@ class _PredefinedHyperglassError(HyperglassError):
class ConfigInvalid(HyperglassError): class ConfigInvalid(HyperglassError):
"""Raised when a config item fails type or option validation.""" """Raised when a config item fails type or option validation."""
def __init__(self, errors: List) -> None: def __init__(self, errors: List[str]) -> None:
"""Parse Pydantic ValidationError.""" """Parse Pydantic ValidationError."""
super().__init__(message=validation_error_message(*errors)) super().__init__(message=validation_error_message(*errors))
@@ -219,7 +189,7 @@ class ParsingError(_UnformattedHyperglassError):
unformatted_msg: Union[Sequence[Dict], str], unformatted_msg: Union[Sequence[Dict], str],
level: str = "danger", level: str = "danger",
**kwargs, **kwargs,
): ) -> None:
"""Format error message with keyword arguments.""" """Format error message with keyword arguments."""
if isinstance(unformatted_msg, Sequence): if isinstance(unformatted_msg, Sequence):
self._message = validation_error_message(*unformatted_msg) self._message = validation_error_message(*unformatted_msg)

View File

@@ -23,7 +23,7 @@ license = "BSD-3-Clause-Clear"
name = "hyperglass" name = "hyperglass"
readme = "README.md" readme = "README.md"
repository = "https://github.com/checktheroads/hyperglass" repository = "https://github.com/checktheroads/hyperglass"
version = "1.0.0-beta.61" version = "1.0.0-beta.62"
[tool.poetry.scripts] [tool.poetry.scripts]
hyperglass = "hyperglass.console:CLI" hyperglass = "hyperglass.console:CLI"