@@ -0,0 +1,84 @@
|
||||
import logging
|
||||
from datetime import datetime
|
||||
|
||||
|
||||
class ColoredConsoleFormatter(logging.Formatter):
|
||||
TIME_COLOR = '\033[38;2;89;89;89m'
|
||||
RESET = '\033[0m'
|
||||
BOLD = '\033[1m'
|
||||
DARK_CYAN = '\033[36m'
|
||||
DARK_YELLOW = '\033[33m'
|
||||
RED = '\033[91m'
|
||||
|
||||
LEVEL_COLORS = {
|
||||
logging.DEBUG: '\033[36m',
|
||||
logging.INFO: '\033[32m',
|
||||
logging.WARNING: '\033[33m',
|
||||
logging.ERROR: RED,
|
||||
logging.CRITICAL: '\033[35m',
|
||||
}
|
||||
|
||||
LEVEL_NAMES = {
|
||||
logging.DEBUG: 'DBG',
|
||||
logging.INFO: 'INF',
|
||||
logging.WARNING: 'WRN',
|
||||
logging.ERROR: 'ERR',
|
||||
logging.CRITICAL: 'CRT',
|
||||
}
|
||||
|
||||
def format(self, record: logging.LogRecord) -> str:
|
||||
timestamp = f'{self.TIME_COLOR}{datetime.fromtimestamp(record.created).strftime("%H:%M:%S")}{self.RESET}'
|
||||
|
||||
level_name = self.LEVEL_NAMES.get(record.levelno, record.levelname[:3])
|
||||
level_color = self.LEVEL_COLORS.get(record.levelno, '')
|
||||
level = f'{level_color}{level_name}{self.RESET}'
|
||||
|
||||
message_color = self.RED if record.levelno >= logging.ERROR else ''
|
||||
message = f'{message_color}{self.BOLD}{record.getMessage()}{self.RESET}'
|
||||
|
||||
# Add extra fields
|
||||
extra_parts = []
|
||||
for key, value in record.__dict__.items():
|
||||
if key not in [
|
||||
'name',
|
||||
'msg',
|
||||
'args',
|
||||
'created',
|
||||
'filename',
|
||||
'funcName',
|
||||
'levelname',
|
||||
'levelno',
|
||||
'lineno',
|
||||
'module',
|
||||
'msecs',
|
||||
'message',
|
||||
'pathname',
|
||||
'process',
|
||||
'processName',
|
||||
'relativeCreated',
|
||||
'thread',
|
||||
'threadName',
|
||||
'exc_info',
|
||||
'exc_text',
|
||||
'stack_info',
|
||||
'app_name',
|
||||
'app_version',
|
||||
'taskName',
|
||||
'color_message',
|
||||
]:
|
||||
value_color = self.RED if key == 'error' else self.DARK_YELLOW
|
||||
extra_parts.append(f'{self.DARK_CYAN}{key}{self.RESET}={value_color}{value}{self.RESET}')
|
||||
|
||||
if extra_parts:
|
||||
message += f' {" ".join(extra_parts)}'
|
||||
|
||||
if record.levelno >= logging.WARNING:
|
||||
location = f'{self.TIME_COLOR}{record.module}:{record.lineno}{self.RESET}'
|
||||
result = f'{timestamp} {level} {location} {message}'
|
||||
else:
|
||||
result = f'{timestamp} {level} {message}'
|
||||
|
||||
if record.exc_info:
|
||||
result += '\n' + self.formatException(record.exc_info)
|
||||
|
||||
return result
|
||||
Reference in New Issue
Block a user