-
Notifications
You must be signed in to change notification settings - Fork 15
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
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
Showing
2 changed files
with
36 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters