Skip to content

Commit

Permalink
patch fix
Browse files Browse the repository at this point in the history
  • Loading branch information
visualDust committed Nov 24, 2023
1 parent 8fc4fa7 commit 61b9f96
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 61 deletions.
3 changes: 1 addition & 2 deletions neetbox/logging/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,5 @@
_cfg = get_module_level_config()
logger.set_log_dir(_cfg["logdir"])
set_log_level(_cfg["level"])
from neetbox.logging.logger import LogSplitStrategies

__all__ = ["logger", "LogSplitStrategies"]
__all__ = ["logger"]
63 changes: 22 additions & 41 deletions neetbox/logging/_writer.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import datetime
import inspect
import io
import json
import os
import pathlib
from dataclasses import dataclass
from datetime import date
from datetime import datetime
from typing import Any, Callable, Iterable, Optional, Union

from rich import print as rprint
Expand All @@ -13,24 +14,10 @@
from neetbox.logging.formatting import LogStyle, colored_text, styled_text


# declare type
# Log writer interface
class LogWriter:
pass


# declare type
class __ConsoleLogWriter:
pass


# declare type
class FileLogWriter:
pass


# declare type
class JsonLogWriter:
pass
def write(self, raw_log):
pass


@dataclass
Expand All @@ -45,13 +32,8 @@ class RawLog:
skip_writers: Optional[list[str]] = None

def write_by(self, writer: LogWriter) -> bool:
name2writerType = {
"console": __ConsoleLogWriter,
"file": FileLogWriter,
"json": JsonLogWriter,
}
for swr in self.skip_writers:
if isinstance(writer, name2writerType[swr]):
if isinstance(writer, RawLog.name2writerType[swr]):
return False # skip this writer, do not write
writer.write(self)
return False
Expand All @@ -61,7 +43,7 @@ def json(self) -> dict:
# prefix
_prefix = self.prefix or _default_style.prefix
# composing datetime
_with_datetime = _with_datetime or _default_style.with_datetime
_with_datetime = self.with_datetime or _default_style.with_datetime
_datetime = ""
if _with_datetime:
_datetime_fmt = self.datetime_format or _default_style.datetime_format
Expand Down Expand Up @@ -96,23 +78,13 @@ def json(self) -> dict:
return {"prefix": _prefix, "datetime": _datetime, "whom": _whom, "msg": self.rich_msg}

def __repr__(self) -> str:
pass

def dumps(s: str):
# todo dump from str
pass


# Log writer interface
class LogWriter:
def write(self, raw_log: RawLog):
pass
return json.dumps(self.json(), default=str)


# ================== CONSOLE LOG WRITER =====================


class __ConsoleLogWriter(metaclass=LogWriter):
class __ConsoleLogWriter(LogWriter):
def write(self, raw_log: RawLog):
_msg_dict = raw_log.json()
_style = raw_log.style
Expand All @@ -121,8 +93,8 @@ def write(self, raw_log: RawLog):
+ _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"],
+ _style.split_char_cmd * min(len(_msg_dict["whom"]), 1)
+ _msg_dict["msg"],
)
rprint(rich_msg)

Expand Down Expand Up @@ -286,7 +258,7 @@ def split_lock(self):
return self._split_lock


class FileLogWriter:
class FileLogWriter(LogWriter):
# class level static pool
PATH_2_FILE_WRITER = {}

Expand Down Expand Up @@ -339,7 +311,7 @@ def write(self, raw_log: RawLog):
# ================== WS LOG WRITER =====================


class __WebSocketLogWriter(metaclass=LogWriter):
class __WebSocketLogWriter(LogWriter):
def __init__(self) -> None:
pass

Expand All @@ -348,3 +320,12 @@ def write(self, raw_log: RawLog):


webSocketLogWriter = __WebSocketLogWriter()


# ================== POST INIT TYPE REF =====================

RawLog.name2writerType = {
"console": __ConsoleLogWriter,
"file": FileLogWriter,
"json": JsonLogWriter,
}
45 changes: 27 additions & 18 deletions neetbox/logging/logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
from rich import print as rprint
from rich.panel import Panel

from neetbox.core import Registry
from neetbox.logging._writer import (
FileLogWriter,
JsonLogWriter,
Expand Down Expand Up @@ -53,8 +52,6 @@ def __ge__(self, other):
return self.value >= other.value


__WHOM_2_LOGGER = Registry("__LOGGERS")

_GLOBAL_LOG_LEVEL = LogLevel.INFO


Expand All @@ -75,6 +72,10 @@ def set_log_level(level: LogLevel):


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 All @@ -86,10 +87,10 @@ def __init__(self, whom, style: Optional[LogStyle] = None):
def __call__(self, whom: Any = None, style: Optional[LogStyle] = None) -> "Logger":
if whom is None:
return DEFAULT_LOGGER
if whom in __WHOM_2_LOGGER:
return __WHOM_2_LOGGER[whom]
__WHOM_2_LOGGER[whom] = Logger(whom=whom, style=style)
return __WHOM_2_LOGGER[whom]
if whom in Logger.__WHOM_2_LOGGER:
return Logger.__WHOM_2_LOGGER[whom]
Logger.__WHOM_2_LOGGER[whom] = Logger(whom=whom, style=style)
return Logger.__WHOM_2_LOGGER[whom]

def log(
self,
Expand All @@ -111,10 +112,18 @@ def log(
if type(skip_writers) is str:
skip_writers = [skip_writers]

_style = self.style
if not _style: # if style not set
if _caller_identity in Logger.__WHOM_2_STYLE: # check for previous style
_style = Logger.__WHOM_2_STYLE[_caller_identity]
else:
_style = LogStyle().randcolor()
Logger.__WHOM_2_STYLE[_caller_identity] = _style

raw_log = RawLog(
rich_msg=_pure_str_message,
caller_identity=_caller_identity,
style=self.style,
style=_style,
prefix=prefix,
datetime_format=datetime_format,
with_identifier=with_identifier,
Expand All @@ -133,43 +142,43 @@ def ok(self, *message, flag="OK"):
self.log(
*message,
prefix=f"[{colored_text(flag, 'green')}]",
into_file=False,
skip_writers=["file"],
traceback=3,
)
self.log(*message, prefix=flag, into_stdout=False, traceback=3)
self.log(*message, prefix=flag, skip_writers=["console"], traceback=3)
return self

def debug(self, *message, flag="DEBUG"):
if _GLOBAL_LOG_LEVEL >= LogLevel.DEBUG:
self.log(
*message,
prefix=f"[{colored_text(flag, 'cyan')}]",
into_file=False,
skip_writers=["file"],
traceback=3,
)
self.log(*message, prefix=flag, into_stdout=False, traceback=3)
self.log(*message, prefix=flag, skip_writers=["console"], traceback=3)
return self

def info(self, *message, flag="INFO"):
if _GLOBAL_LOG_LEVEL >= LogLevel.INFO:
self.log(
*message,
prefix=f"[{colored_text(flag, 'white')}]",
into_file=False,
skip_writers=["file"],
traceback=3,
)
self.log(*message, prefix=flag, into_stdout=False, traceback=3)
self.log(*message, prefix=flag, skip_writers=["console"], traceback=3)
return self

def warn(self, *message, flag="WARNING"):
if _GLOBAL_LOG_LEVEL >= LogLevel.WARNING:
self.log(
*message,
prefix=f"[{colored_text(flag, 'yellow')}]",
into_file=False,
skip_writers=["file"],
traceback=3,
)
self.log(*message, prefix=flag, into_stdout=False, traceback=3)
self.log(*message, prefix=flag, skip_writers=["console"], traceback=3)
return self

def err(self, err, flag="ERROR", reraise=False):
Expand All @@ -179,10 +188,10 @@ def err(self, err, flag="ERROR", reraise=False):
self.log(
str(err),
prefix=f"[{colored_text(flag,'red')}]",
into_file=False,
skip_writers=["file"],
traceback=3,
)
self.log(str(err), prefix=flag, into_stdout=False, traceback=3)
self.log(str(err), prefix=flag, skip_writers=["console"], traceback=3)
if reraise:
raise err
return self
Expand Down

0 comments on commit 61b9f96

Please sign in to comment.