Skip to content

Commit

Permalink
fixed logger errors for previous patch works
Browse files Browse the repository at this point in the history
  • Loading branch information
visualDust committed Nov 24, 2023
1 parent 61b9f96 commit a5c298c
Show file tree
Hide file tree
Showing 4 changed files with 22 additions and 29 deletions.
7 changes: 4 additions & 3 deletions neetbox/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,16 +60,17 @@ def init(path=None, load=False, **kwargs) -> bool:
from neetbox.logging.logger import Logger

logger = Logger("NEETBOX") # builtin standalone logger
logger.ok(f"Loaded workspace config from {config_file_path}.")
logger.ok(f"found workspace config from {config_file_path}.")
_try_attach_daemon() # try attach daemon
logger.debug(f"running post init...")
post_init()
return True
except Exception as e:
from neetbox.logging.logger import Logger

logger = Logger("NEETBOX") # builtin standalone logger
logger.err(f"Failed to load config from {config_file_path}: {e}")
return False
logger.err(f"failed to load config from {config_file_path}: {e}")
raise e


is_in_daemon_process = (
Expand Down
30 changes: 16 additions & 14 deletions neetbox/logging/_writer.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,13 @@
import os
import pathlib
from dataclasses import dataclass
from datetime import date
from datetime import datetime
from datetime import date, datetime
from typing import Any, Callable, Iterable, Optional, Union

from rich import print as rprint

from neetbox.logging import formatting
from neetbox.logging.formatting import LogStyle, colored_text, styled_text
from neetbox.utils import formatting


# Log writer interface
Expand All @@ -23,18 +22,20 @@ def write(self, raw_log):
@dataclass
class RawLog:
rich_msg: str
caller_identity: Any
style: LogStyle
caller_identity: Any
whom: Any = None
prefix: Optional[str] = None
datetime_format: Optional[str] = None
with_identifier: Optional[bool] = None
with_datetime: Optional[bool] = None
skip_writers: Optional[list[str]] = None

def write_by(self, writer: LogWriter) -> bool:
for swr in self.skip_writers:
if isinstance(writer, RawLog.name2writerType[swr]):
return False # skip this writer, do not write
if self.skip_writers: # if skipping any writers
for swr in self.skip_writers:
if isinstance(writer, RawLog.name2writerType[swr]):
return False # skip this writer, do not write
writer.write(self)
return False

Expand All @@ -54,9 +55,9 @@ def json(self) -> dict:
_with_identifier = self.with_identifier or _default_style.with_identifier
if _with_identifier:
_caller_identity = self.caller_identity
_whom = str(_caller_identity) # check identity
_whom = str(self.whom) # check identity
id_seq = []
if _caller_identity is None: # if using default logger, tracing back to the caller
if self.whom is None: # if using default logger, tracing back to the caller
file_level = True
_whom = ""
if _caller_identity.module_name and _default_style.trace_level >= 2:
Expand Down Expand Up @@ -88,13 +89,13 @@ class __ConsoleLogWriter(LogWriter):
def write(self, raw_log: RawLog):
_msg_dict = raw_log.json()
_style = raw_log.style
rich_msg = (
rich_msg = str(
_msg_dict["prefix"]
+ _msg_dict["datetime"]
+ _style.split_char_cmd * min(len(_msg_dict["datetime"]), 1)
+ styled_text(_msg_dict["whom"], style=_style)
+ _style.split_char_cmd * min(len(_msg_dict["whom"]), 1)
+ _msg_dict["msg"],
+ _msg_dict["msg"]
)
rprint(rich_msg)

Expand Down Expand Up @@ -276,9 +277,10 @@ def __new__(cls, path, *args, **kwargs):
raise Exception(f"Could not find dictionary {dirname}")
real_path = os.path.join(dirname, filename)
if file_abs_path not in FileLogWriter.PATH_2_FILE_WRITER:
FileLogWriter.PATH_2_FILE_WRITER[file_abs_path] = object.__new__(
cls, real_path, *args, **kwargs
)
newWriter = LogWriter.__new__(cls)
newWriter.file_writer = open(real_path, "a", encoding="utf-8", buffering=1)
FileLogWriter.PATH_2_FILE_WRITER[file_abs_path] = newWriter

return FileLogWriter.PATH_2_FILE_WRITER[file_abs_path]

def __init__(self, path) -> None:
Expand Down
3 changes: 2 additions & 1 deletion neetbox/logging/logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ class Logger:
# global static
__WHOM_2_LOGGER = {}
__WHOM_2_STYLE = {}

def __init__(self, whom, style: Optional[LogStyle] = None):
self.whom: Any = whom
self.style: Optional[LogStyle] = style
Expand Down Expand Up @@ -123,6 +123,7 @@ def log(
raw_log = RawLog(
rich_msg=_pure_str_message,
caller_identity=_caller_identity,
whom=self.whom,
style=_style,
prefix=prefix,
datetime_format=datetime_format,
Expand Down
11 changes: 0 additions & 11 deletions tests/test_logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,14 +37,3 @@ def b(self):
self.logger.log("from class B")

B().b()


def test_logger_catch():
from neetbox.logging import logger

@logger.catch(reraise=False)
def my_function(x, y, z):
# An error? It's caught anyway!
return 1 / (x + y + z)

my_function(0, 0, 0)

0 comments on commit a5c298c

Please sign in to comment.