Skip to content

Commit

Permalink
refactor: use colorama for colorful logging
Browse files Browse the repository at this point in the history
  • Loading branch information
KnownBlackHat committed Jul 14, 2024
1 parent 2028bcb commit 850a66c
Show file tree
Hide file tree
Showing 5 changed files with 86 additions and 116 deletions.
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,4 @@ repos:
hooks:
- id: isort
exclude: '^(env)'
args: ["profile", "--black"]
args: ["--profile", "black"]
72 changes: 1 addition & 71 deletions mr_robot/__main__.py
Original file line number Diff line number Diff line change
@@ -1,88 +1,18 @@
import asyncio
import atexit
import json
import logging.config
import logging.handlers
import signal
import sys
from pathlib import Path

import coloredlogs
import disnake
import httpx
from dotenv import load_dotenv
from sqlalchemy import event
from sqlalchemy.engine import Engine

from mr_robot.bot import MrRobot
from mr_robot.constants import Client, Database

load_dotenv()


def setup_logging_modern() -> None:
with open(Client.logging_config_file, "r") as file:
config = json.load(file)
logging.config.dictConfig(config)
queue_handler = logging.getHandlerByName("queue_handler")
if queue_handler is not None:
queue_handler.listener.start() # type: ignore[reportAttributeAccessIssue]
atexit.register(queue_handler.listener.stop) # type: ignore[reportAttributeAccessIssue]


def setup_logging() -> None:
root_logger = logging.getLogger()

log_file = Path(Client.log_file_name)
log_file.parent.mkdir(exist_ok=True)

formatter = "[ %(levelname)s | %(name)s | %(module)s | L%(lineno)d ] %(asctime)s: %(message)s"
file_formatter = logging.Formatter(
"[ %(levelname)s | %(name)s | %(module)s | %(funcName)s | %(filename)s | L%(lineno)d ] %(asctime)s: %(message)s"
)

file_handler = logging.handlers.RotatingFileHandler(
log_file,
mode="a",
# File handler rotates log every 5 MB
maxBytes=5 * (2**20),
backupCount=10,
)
file_handler.setFormatter(file_formatter)
root_logger.addHandler(file_handler)

# console_handler = logging.StreamHandler()
# console_handler.setFormatter(formatter)
# root_logger.addHandler(console_handler)

file_handler.setLevel(logging.DEBUG)
# console_handler.setLevel(logging.INFO)

coloredlogs.DEFAULT_LEVEL_STYLES = {
**coloredlogs.DEFAULT_LEVEL_STYLES,
"critical": {"color": "red"},
"warning": {"color": "yellow"},
"info": {"color": "green"},
"debug": {"color": "white"},
}
coloredlogs.install(
level=logging.DEBUG, stream=sys.stdout, logger=root_logger, fmt=formatter
)

root_logger.setLevel(logging.DEBUG)
logging.getLogger("httpx").setLevel(logging.WARNING)
logging.getLogger("mafic").setLevel(logging.WARNING)
logging.getLogger("httpcore").setLevel(logging.WARNING)
logging.getLogger("disnake").setLevel(logging.INFO)
logging.getLogger("sqlalchemy.engine").setLevel(logging.WARNING)
logging.getLogger("core").setLevel(logging.WARNING)
logging.getLogger("sqlalchemy.engine.Engine").setLevel(logging.WARNING)
logging.getLogger("sqlalchemy.pool").setLevel(logging.WARNING)
logging.getLogger("sqlalchemy.orm").setLevel(logging.WARNING)
logging.getLogger("aiosqlite").setLevel(logging.WARNING)
logging.getLogger("streamlink").disabled = True

root_logger.info("Logger Initialized!")
from mr_robot.log import setup_logging


@event.listens_for(Engine, "connect")
Expand Down
82 changes: 82 additions & 0 deletions mr_robot/log.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import atexit
import json
import logging.config
import logging.handlers
from pathlib import Path

import colorama

from mr_robot.constants import Client


class LogFormatter(logging.Formatter):
colormap = {
logging.DEBUG: colorama.Fore.MAGENTA,
logging.INFO: colorama.Fore.BLUE,
logging.WARNING: colorama.Fore.YELLOW,
logging.ERROR: colorama.Fore.RED,
logging.CRITICAL: colorama.Fore.WHITE,
}

def __init__(self, format: str) -> None:
super().__init__(format)

def format(self, record: logging.LogRecord) -> str:
record.levelname = f"{self.colormap.get(record.levelno)}{record.levelname}{colorama.Fore.RESET}"
return super().format(record)


def setup_logging_modern() -> None:
with open(Client.logging_config_file, "r") as file:
config = json.load(file)
logging.config.dictConfig(config)
queue_handler = logging.getHandlerByName("queue_handler")
if queue_handler is not None:
queue_handler.listener.start() # type: ignore[reportAttributeAccessIssue]
atexit.register(queue_handler.listener.stop) # type: ignore[reportAttributeAccessIssue]


def setup_logging() -> None:
root_logger = logging.getLogger()

log_file = Path(Client.log_file_name)
log_file.parent.mkdir(exist_ok=True)

formatter = LogFormatter(
"[ %(levelname)s | %(name)s | %(module)s | L%(lineno)d ] %(asctime)s: %(message)s"
)
file_formatter = logging.Formatter(
"[ %(levelname)s | %(name)s | %(module)s | %(funcName)s | %(filename)s | L%(lineno)d ] %(asctime)s: %(message)s"
)

file_handler = logging.handlers.RotatingFileHandler(
log_file,
mode="a",
# File handler rotates log every 5 MB
maxBytes=5 * (2**20),
backupCount=10,
)
file_handler.setFormatter(file_formatter)
root_logger.addHandler(file_handler)

console_handler = logging.StreamHandler()
console_handler.setFormatter(formatter)
root_logger.addHandler(console_handler)

file_handler.setLevel(logging.DEBUG)
console_handler.setLevel(logging.INFO)

root_logger.setLevel(logging.DEBUG)
logging.getLogger("httpx").setLevel(logging.WARNING)
logging.getLogger("mafic").setLevel(logging.WARNING)
logging.getLogger("httpcore").setLevel(logging.WARNING)
logging.getLogger("disnake").setLevel(logging.INFO)
logging.getLogger("sqlalchemy.engine").setLevel(logging.WARNING)
logging.getLogger("core").setLevel(logging.WARNING)
logging.getLogger("sqlalchemy.engine.Engine").setLevel(logging.WARNING)
logging.getLogger("sqlalchemy.pool").setLevel(logging.WARNING)
logging.getLogger("sqlalchemy.orm").setLevel(logging.WARNING)
logging.getLogger("aiosqlite").setLevel(logging.WARNING)
logging.getLogger("streamlink").disabled = True

root_logger.info("Logger Initialized!")
44 changes: 1 addition & 43 deletions poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ httpx = "^0.27.0"
googletrans-py = "^4.0.0"
mafic = "~2.10.0"
sqlalchemy = "^2.0.31"
coloredlogs = "^15.0.1"
colorama = "^0.4.6"

[tool.poetry.group.dev.dependencies]
black = "^24.4.2"
Expand Down

0 comments on commit 850a66c

Please sign in to comment.