Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 23 additions & 21 deletions src/twinkle/utils/logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ def _parse_log_level(level) -> int:
return logging.INFO


log_level = _parse_log_level(os.getenv('LOG_LEVEL', 'INFO'))
log_level = _parse_log_level(os.getenv("LOG_LEVEL", "INFO"))


# Avoid circular reference
Expand All @@ -46,22 +46,22 @@ def _is_local_master():

# old format
# formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger_format = logging.Formatter('[%(asctime)s][%(levelname)s:%(name)s] %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
logger_format = logging.Formatter("[%(asctime)s][%(levelname)s:%(name)s] %(message)s", datefmt="%Y-%m-%d %H:%M:%S")

info_set = set()
warning_set = set()


def _rank_info(self, msg, *args, ranks='master', **kwargs):
def _rank_info(self, msg, *args, ranks="master", **kwargs):
"""Log at INFO level with rank control.

Args:
ranks: 'master' (default) - only local rank 0;
'all' - every rank (prefixed with rank id).
"""
if ranks == 'all':
if ranks == "all":
rank = Platform.get_local_rank()
tagged = f'[rank{rank}] {msg}'
tagged = f"[rank{rank}] {msg}"
if _is_local_master():
self._original_info(tagged, *args, **kwargs)
else:
Expand All @@ -71,16 +71,16 @@ def _rank_info(self, msg, *args, ranks='master', **kwargs):
self._original_info(msg, *args, **kwargs)


def _rank_warning(self, msg, *args, ranks='master', **kwargs):
def _rank_warning(self, msg, *args, ranks="master", **kwargs):
"""Log at WARNING level with rank control.

Args:
ranks: 'master' (default) - only local rank 0;
'all' - every rank (prefixed with rank id).
"""
if ranks == 'all':
if ranks == "all":
rank = Platform.get_local_rank()
tagged = f'[rank{rank}] {msg}'
tagged = f"[rank{rank}] {msg}"
if _is_local_master():
self._original_warning(tagged, *args, **kwargs)
else:
Expand All @@ -103,26 +103,28 @@ def warning_if(self, msg, cond, *args, **kwargs):


def info_once(self, msg, *args, **kwargs):
hash_id = kwargs.get('hash_id') or msg
# ``args`` are the printf-style substitutions for ``msg``; dropping them here (as an earlier
# version did by calling ``self.info(msg)``) left the raw ``%s`` in the output. The hash id
# stays the unformatted template so every call site logs exactly once regardless of its args.
hash_id = kwargs.get("hash_id") or msg
if hash_id in info_set:
return
info_set.add(hash_id)
self.info(msg)
self.info(msg, *args)


def warning_once(self, msg, *args, **kwargs):
hash_id = kwargs.get('hash_id') or msg
hash_id = kwargs.get("hash_id") or msg
if hash_id in warning_set:
return
warning_set.add(hash_id)
self.warning(msg)
self.warning(msg, *args)


def get_logger(log_file: Optional[str] = None,
log_level: Optional[int] = None,
file_mode: str = 'w',
only_local_master: bool = True) -> logging.Logger:
""" Get logging logger
def get_logger(
log_file: str | None = None, log_level: int | None = None, file_mode: str = "w", only_local_master: bool = True
) -> logging.Logger:
"""Get logging logger

Args:
log_file: Log filename, if specified, file handler will be added to
Expand All @@ -133,10 +135,10 @@ def get_logger(log_file: Optional[str] = None,
only_local_master: Output log only when it's local master, default True.
"""
if log_level is None:
log_level = _parse_log_level(os.getenv('LOG_LEVEL', 'INFO'))
log_level = _parse_log_level(os.getenv("LOG_LEVEL", "INFO"))
elif isinstance(log_level, str):
log_level = _parse_log_level(log_level)
logger_name = __name__.split('.')[0]
logger_name = __name__.split(".")[0]
logger = logging.getLogger(logger_name)
logger.propagate = False
if logger_name in init_loggers:
Expand Down Expand Up @@ -205,8 +207,8 @@ def add_file_handler_if_needed(logger, log_file, file_mode, log_level):
if isinstance(handler, logging.FileHandler):
return

if importlib.util.find_spec('torch') is not None:
is_worker0 = int(os.getenv('LOCAL_RANK', -1)) in {-1, 0}
if importlib.util.find_spec("torch") is not None:
is_worker0 = int(os.getenv("LOCAL_RANK", -1)) in {-1, 0}
else:
is_worker0 = True

Expand Down
Loading