Skip to content

Commit

Permalink
logs: Add colored output
Browse files Browse the repository at this point in the history
Make the log output colored depending on the log level. This will make
it much easier to quickly spot errors and warnings in the output, and
also looks cooler.

Control characters for colors are only added if the output is a TTY, so
the output can be redirected to a file without any issues.

Signed-off-by: Mykyta Poturai <[email protected]>
  • Loading branch information
Deedone committed Oct 29, 2024
1 parent b50a902 commit fcf09fc
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
34 changes: 34 additions & 0 deletions moulin/log_utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# SPDX-License-Identifier: Apache-2.0
# Copyright 2024 EPAM Systems


import logging
import sys


class ColoredFormatter(logging.Formatter):
# Define color codes
COLORS = {
'DEBUG': '\033[94m', # Blue
'INFO': '\033[92m', # Green
'WARNING': '\033[93m', # Yellow
'ERROR': '\033[91m', # Red
'CRITICAL': '\033[1;91m' # Bold Red
}
RESET = '\033[0m' # Reset color

def format(self, record):
log_color = self.COLORS.get(record.levelname, self.RESET)
message = super().format(record)

if sys.stderr.isatty():
return f"{log_color}{message}{self.RESET}"
else:
return message


def build_handlers(log_format: str) -> list[logging.Handler]:
formatter = ColoredFormatter(log_format)
handler = logging.StreamHandler()
handler.setFormatter(formatter)
return [handler]
3 changes: 2 additions & 1 deletion moulin/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
from moulin.build_conf import MoulinConfiguration
import moulin.rouge
import moulin.rouge.block_entry
from moulin.log_utils import build_handlers

log = logging.getLogger(__name__)

Expand Down Expand Up @@ -88,7 +89,7 @@ def _handle_shared_opts(description: str,
loglevel = logging.INFO
if args.verbose:
loglevel = logging.DEBUG
logging.basicConfig(level=loglevel, format="[%(levelname)s] %(message)s")
logging.basicConfig(level=loglevel, handlers=build_handlers("[%(levelname)s] %(message)s"))

local_conf_file = _get_conf_file(args.conf)

Expand Down

0 comments on commit fcf09fc

Please sign in to comment.