fix(common): Fixes ordered_dict_logger saving when file_path is not supplied.

This commit is contained in:
Gustavo Rosa 2023-01-26 17:24:53 -03:00
Родитель 428ebc3d31
Коммит 5e2056d14c
1 изменённых файлов: 13 добавлений и 14 удалений

Просмотреть файл

@ -21,7 +21,7 @@ class OrderedDictLogger:
"""Log and save data in a hierarchical YAML structure.""" """Log and save data in a hierarchical YAML structure."""
def __init__( def __init__(
self, source: Optional[str] = None, file_path: Optional[str] = "archai.log.yaml", delay: Optional[float] = 30.0 self, source: Optional[str] = None, file_path: Optional[str] = None, delay: Optional[float] = 60.0
) -> None: ) -> None:
"""Initialize the logger. """Initialize the logger.
@ -43,9 +43,10 @@ class OrderedDictLogger:
self.paths = [[""]] self.paths = [[""]]
self.stack = [OrderedDict()] self.stack = [OrderedDict()]
if os.path.exists(self.file_path): if self.file_path:
backup_file_path = pathlib.Path(self.file_path) if os.path.exists(self.file_path):
backup_file_path.rename(backup_file_path.with_suffix(f".{str(int(time.time()))}.yaml")) backup_file_path = pathlib.Path(self.file_path)
backup_file_path.rename(backup_file_path.with_suffix(f".{str(int(time.time()))}.yaml"))
def __enter__(self) -> OrderedDictLogger: def __enter__(self) -> OrderedDictLogger:
return self return self
@ -100,25 +101,23 @@ class OrderedDictLogger:
return "/".join(itertools.chain.from_iterable(self.paths[1:])) return "/".join(itertools.chain.from_iterable(self.paths[1:]))
def save(self, file_path: Optional[str] = None) -> None: def save(self) -> None:
"""Save the current log data to an output file. """Save the current log data to an output file.
Args: This method only saves to a file if a valid `file_path` has been provided
file_path: File path to save the log data to. If `None`, in the constructor.
defaults to the file path provided during initialization.
""" """
file_path = file_path or self.file_path if self.file_path:
with open(self.file_path, "w") as f:
with open(file_path, "w") as f: yaml.dump(self.root_node, f)
yaml.dump(self.root_node, f)
def load(self, file_path: str) -> None: def load(self, file_path: str) -> None:
"""Load log data from an input file. """Load log data from an input file.
Args: Args:
file_path (str): File path to load data from. file_path: File path to load data from.
""" """
@ -297,7 +296,7 @@ def get_global_logger() -> OrderedDictLogger:
try: try:
logger = OrderedDictLogger.get_global_instance() logger = OrderedDictLogger.get_global_instance()
except: except:
OrderedDictLogger.set_global_instance(OrderedDictLogger()) OrderedDictLogger.set_global_instance(OrderedDictLogger(file_path="archai.log.yaml", delay=30.0))
logger = OrderedDictLogger.get_global_instance() logger = OrderedDictLogger.get_global_instance()
return logger return logger