Skip to content

Commit

Permalink
⚡ [Enhance] FileLogger: replace success char for mono-space, add pref…
Browse files Browse the repository at this point in the history
…ix param, and set prefix to empty by default if no mesg_type specified
  • Loading branch information
Hansimov committed Jan 27, 2025
1 parent 3b40a0a commit 2b76ece
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 5 deletions.
3 changes: 3 additions & 0 deletions example.py
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,9 @@ def test_dict_to_str():
def test_file_logger():
file_logger = FileLogger(Path(__file__).parent / "test.log")
file_logger.log("This is an error message", "error")
file_logger.log("This is a default message")
file_logger.log("This is a prefixed message", prefix="+")
file_logger.log("This is a success message", msg_type="success")


def test_align_dict_list():
Expand Down
17 changes: 12 additions & 5 deletions src/tclogger/files.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from typing import Literal, Union


MSG_PREFIXES = {"note": ">", "error": "×", "success": ""}
MSG_PREFIXES = {"note": ">", "error": "×", "success": ""}


class FileLogger:
Expand All @@ -20,14 +20,21 @@ def __init__(self, log_path: Union[str, Path], lock: threading.Lock = None):
def log(
self,
msg: str,
msg_type: Literal["note", "error", "success"] = "note",
msg_type: Literal["note", "error", "success"] = None,
prefix: str = None,
add_now: bool = True,
):
prefix = MSG_PREFIXES.get(msg_type, ">")
if prefix:
prefix_str = f"{prefix} "
elif msg_type:
prefix_str = MSG_PREFIXES.get(msg_type, "*") + " "
else:
prefix_str = ""

if add_now:
line = f"{prefix} [{get_now_str()}] {msg}\n"
line = f"{prefix_str}[{get_now_str()}] {msg}\n"
else:
line = f"{prefix} {msg}\n"
line = f"{prefix_str}{msg}\n"
with self.lock:
with open(self.log_path, "a") as f:
f.write(line)

0 comments on commit 2b76ece

Please sign in to comment.