Skip to content

Commit

Permalink
feat: Add option to disable log levels in logs
Browse files Browse the repository at this point in the history
  • Loading branch information
igrek51 committed Jul 11, 2024
1 parent 2365537 commit 949fe83
Show file tree
Hide file tree
Showing 4 changed files with 29 additions and 18 deletions.
8 changes: 8 additions & 0 deletions docs/example/sublog-init.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
from nuclear.sublog import logger, init_logs


init_logs(show_time=False, show_log_level=False)

logger.debug('checking engine', temperature=85.0, pressure='12kPa')
logger.info('ignition ready', speed='zero')
logger.warning('Attention')
29 changes: 18 additions & 11 deletions nuclear/sublog/logging.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@

from nuclear.sublog.context_error import ContextError
from nuclear.sublog.exception import extended_exception_details
from nuclear.utils.collections import coalesce2, filter_not_none
from nuclear.utils.collections import coalesce
from nuclear.utils.env import is_env_flag_enabled
from nuclear.utils.strings import strip_ansi_colors

Expand All @@ -29,11 +29,14 @@

def init_logs(
show_time: Optional[bool] = None,
show_log_level: Optional[bool] = None,
):
"""
Configure loggers: formatters, handlers and log levels
:param show_time: if True, formatted time will be displayed in each log message,
None will use default value
:param show_time: True to display formatted time in each log message,
False to turn it off, None to use the default
:param show_log_level: True to display log level in each log message,
False to turn it off, None to use the default
"""
logging_kwargs: Dict[str, Any] = {
'stream': sys.stdout,
Expand All @@ -49,17 +52,17 @@ def init_logs(
for handler in logging.getLogger().handlers:
handler.setFormatter(StructuredFormatter())
else:
log_time_show: bool = coalesce2(show_time, is_env_flag_enabled('NUCLEAR_LOG_TIME', 'true'))
_show_log_time: bool = coalesce(show_time, is_env_flag_enabled('NUCLEAR_LOG_TIME', 'true'))
_show_log_level: bool = coalesce(show_log_level, is_env_flag_enabled('NUCLEAR_LOG_LEVEL_SHOW', 'true'))
logging.basicConfig(**logging_kwargs)
for handler in logging.getLogger().handlers:
handler.setFormatter(ColoredFormatter(log_time_show))
handler.setFormatter(ColoredFormatter(_show_log_time, _show_log_level))

log_level: str = os.environ.get('NUCLEAR_LOG_LEVEL', 'debug')
level = _get_logging_level(log_level)
root_logger = logging.getLogger(LOGGING_LOGGER_NAME)
root_logger.setLevel(level)
_log_state['init'] = True
print('twice')


def init_logs_once():
Expand Down Expand Up @@ -161,9 +164,9 @@ def add_context(context_name: str, log: bool = False, **ctx):


class ColoredFormatter(logging.Formatter):
def __init__(self, log_time_show: bool):
def __init__(self, log_time_show: bool, log_level_show: bool):
logging.Formatter.__init__(self)
self.log_level_show: bool = is_env_flag_enabled('NUCLEAR_LOG_LEVEL_SHOW', 'true')
self.log_level_show: bool = log_level_show
self.log_time_show: bool = log_time_show

log_level_templates = {
Expand All @@ -175,10 +178,14 @@ def __init__(self, log_time_show: bool):
}

def format(self, record: logging.LogRecord) -> str:
part_levelname = self.log_level_templates.get(record.levelname, record.levelname) if self.log_level_show else None
part_message = record.msg
parts: List[str] = []
part_time = self.format_time()
parts: List[str] = filter_not_none([part_time, part_levelname, part_message])
if part_time:
parts.append(part_time)
if self.log_level_show:
part_levelname = self.log_level_templates.get(record.levelname, record.levelname)
parts.append(part_levelname)
parts.append(record.msg)
line = ' '.join(parts)
if not sys.stdout.isatty():
line = strip_ansi_colors(line)
Expand Down
8 changes: 2 additions & 6 deletions nuclear/utils/collections.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,12 +48,8 @@ def filter_not_none(items: List[Optional[T]]) -> List[T]:
return [item for item in items if item is not None]


def coalesce(*items: Optional[T]) -> Optional[T]:
def coalesce(*items: Optional[T]) -> T:
for item in items:
if item is not None:
return item
return None


def coalesce2(item: Optional[T], default: T) -> T:
return item if item is not None else default
raise ValueError('all items are None')
2 changes: 1 addition & 1 deletion nuclear/version.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__version__ = "2.2.3"
__version__ = "2.2.4"

0 comments on commit 949fe83

Please sign in to comment.