Files
NexQuant/rdagent/log/storage.py
T

112 lines
3.4 KiB
Python
Raw Normal View History

2024-07-16 20:35:42 +08:00
import json
import pickle
import re
2024-07-17 15:00:13 +08:00
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Generator, Literal
2024-07-16 20:35:42 +08:00
2024-07-19 14:16:54 +08:00
from .base import Message, Storage
from .utils import gen_datetime
2024-07-16 20:35:42 +08:00
2024-07-25 15:20:04 +08:00
LOG_LEVEL = Literal["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"]
2024-07-17 15:00:13 +08:00
def _remove_empty_dir(path: Path) -> None:
"""
Recursively remove empty directories.
This function will remove the directory if it is empty after removing its subdirectories.
"""
if path.is_dir():
sub_dirs = [sub for sub in path.iterdir() if sub.is_dir()]
for sub in sub_dirs:
_remove_empty_dir(sub)
if not any(path.iterdir()):
path.rmdir()
2024-07-16 20:35:42 +08:00
class FileStorage(Storage):
"""
The info are logginged to the file systems
TODO: describe the storage format
"""
def __init__(self, path: str | Path) -> None:
2024-07-16 20:35:42 +08:00
self.path = Path(path)
2024-07-17 15:00:13 +08:00
def log(
self,
obj: object,
tag: str = "",
2024-07-17 15:00:13 +08:00
timestamp: datetime | None = None,
save_type: Literal["json", "text", "pkl"] = "pkl",
2024-07-25 15:20:04 +08:00
**kwargs: Any,
) -> str | Path:
2024-07-16 20:35:42 +08:00
# TODO: We can remove the timestamp after we implement PipeLog
timestamp = gen_datetime(timestamp)
2024-07-17 15:00:13 +08:00
cur_p = self.path / tag.replace(".", "/")
2024-07-16 20:35:42 +08:00
cur_p.mkdir(parents=True, exist_ok=True)
path = cur_p / f"{timestamp.strftime('%Y-%m-%d_%H-%M-%S-%f')}.log"
if save_type == "json":
path = path.with_suffix(".json")
with path.open("w") as f:
try:
json.dump(obj, f)
except TypeError:
json.dump(json.loads(str(obj)), f)
return path
elif save_type == "pkl":
path = path.with_suffix(".pkl")
with path.open("wb") as f:
pickle.dump(obj, f)
return path
elif save_type == "text":
obj = str(obj)
with path.open("w") as f:
f.write(obj)
return path
2024-07-19 14:16:54 +08:00
log_pattern = re.compile(
r"(?P<timestamp>\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{3}) \| "
r"(?P<level>DEBUG|INFO|WARNING|ERROR|CRITICAL) *\| "
r"(?P<caller>.+:.+:\d+) - "
)
def iter_msg(self, tag: str | None = None) -> Generator[Message, None, None]:
2024-07-19 14:16:54 +08:00
msg_l = []
2025-05-16 18:29:59 +08:00
pkl_files = "**/*.pkl" if tag is None else f"**/{tag.replace('.','/')}/**/*.pkl"
for file in self.path.glob(pkl_files):
if file.name == "debug_llm.pkl":
continue
2025-05-16 18:29:59 +08:00
pkl_log_tag = ".".join(file.relative_to(self.path).as_posix().replace("/", ".").split(".")[:-3])
2024-07-30 17:23:05 +08:00
pid = file.parent.name
with file.open("rb") as f:
content = pickle.load(f)
timestamp = datetime.strptime(file.stem, "%Y-%m-%d_%H-%M-%S-%f").replace(tzinfo=timezone.utc)
2025-05-16 18:29:59 +08:00
m = Message(tag=pkl_log_tag, level="INFO", timestamp=timestamp, caller="", pid_trace=pid, content=content)
2024-07-30 17:23:05 +08:00
msg_l.append(m)
2024-07-19 14:16:54 +08:00
msg_l.sort(key=lambda x: x.timestamp)
for m in msg_l:
yield m
def truncate(self, time: datetime) -> None:
for file in self.path.glob("**/*.pkl"):
timestamp = datetime.strptime(file.stem, "%Y-%m-%d_%H-%M-%S-%f").replace(tzinfo=timezone.utc)
if timestamp > time:
file.unlink()
_remove_empty_dir(self.path)
def __str__(self) -> str:
return f"FileStorage({self.path})"