Skip to content

Commit 312daa2

Browse files
Fixed logging output routing and added colorized logging (#205, #206)
- Routed info/warning messages to stdout, errors to stderr - Added ANSI color codes for different log levels - Implemented ColoredFormatter with specified color scheme
1 parent 8755a20 commit 312daa2

1 file changed

Lines changed: 47 additions & 8 deletions

File tree

scripts/shared.py

Lines changed: 47 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
# Standard library
22
import logging
33
import os
4+
import sys
45
from datetime import datetime, timezone
56

67
# Third-party
@@ -113,12 +114,50 @@ def paths_update(logger, paths, old_quarter, new_quarter):
113114
return paths
114115

115116

117+
class ColoredFormatter(logging.Formatter):
118+
"""Adds colors to log messages."""
119+
120+
COLORS = {
121+
logging.DEBUG: "\033[90m", # bright black
122+
logging.INFO: "\033[37m", # white
123+
logging.WARNING: "\033[103m", # bright yellow
124+
logging.ERROR: "\033[33m", # yellow
125+
logging.CRITICAL: "\033[31m", # red
126+
}
127+
RESET = "\033[0m"
128+
129+
def format(self, record):
130+
message = super().format(record)
131+
color = self.COLORS.get(record.levelno, "")
132+
if color:
133+
return f"{color}{message}{self.RESET}"
134+
return message
135+
136+
116137
def setup(current_file):
117138
# Set up logging
118-
logging.basicConfig(
119-
level=logging.INFO,
120-
format="%(asctime)s - %(levelname)s - %(module)s - %(message)s",
139+
root = logging.getLogger()
140+
root.handlers.clear()
141+
root.setLevel(logging.INFO)
142+
143+
formatter = ColoredFormatter(
144+
"%(asctime)s - %(levelname)s - %(module)s - %(message)s"
121145
)
146+
147+
# Info/warning to stdout
148+
stdout_handler = logging.StreamHandler(sys.stdout)
149+
stdout_handler.setLevel(logging.DEBUG)
150+
stdout_handler.setFormatter(formatter)
151+
stdout_handler.addFilter(lambda r: r.levelno < logging.ERROR)
152+
153+
# Errors to stderr
154+
stderr_handler = logging.StreamHandler(sys.stderr)
155+
stderr_handler.setLevel(logging.ERROR)
156+
stderr_handler.setFormatter(formatter)
157+
158+
root.addHandler(stdout_handler)
159+
root.addHandler(stderr_handler)
160+
122161
logger = logging.getLogger(__name__)
123162

124163
# Datetime
@@ -220,11 +259,11 @@ def update_readme(
220259
entry_start_index = lines.index(entry_start_line)
221260
entry_end_index = lines.index(entry_end_line)
222261
# Include any trailing empty/whitespace-only lines
223-
while entry_end_index + 1 < len(lines):
224-
if not lines[entry_end_index + 1].strip():
225-
entry_end_index += 1
226-
else:
227-
break
262+
while (
263+
entry_end_index + 1 < len(lines)
264+
and not lines[entry_end_index + 1].strip()
265+
):
266+
entry_end_index += 1
228267
# Initalize variables of entry is not present
229268
else:
230269
entry_start_index = None

0 commit comments

Comments
 (0)