Skip to content

Commit

Permalink
feat: Add logging module with ansi format for tty
Browse files Browse the repository at this point in the history
  • Loading branch information
MissterHao committed Feb 10, 2023
1 parent 1a58b22 commit 85e160c
Show file tree
Hide file tree
Showing 5 changed files with 117 additions and 0 deletions.
57 changes: 57 additions & 0 deletions dysession/logger/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import logging
import sys
from enum import Enum, auto
from functools import lru_cache
from typing import Optional

from handler.colorful_console import ColorfulConsoleLoggerHandler


class LoggingType(Enum):

PLAINTEXT_CONSOLE = auto()
COLOR_CONSOLE = auto()
FILE = auto()
CONSOLE = auto()


@lru_cache
def is_tty() -> bool:
"""Hepler function with lru_cache"""
return sys.stdout.isatty()


def get_logger(
logger_name: str = "dysession",
logger_type: LoggingType = LoggingType.CONSOLE,
level: int = logging.DEBUG,
) -> logging.Logger:

logger = logging.getLogger(logger_name)
format = logging.Formatter(
"[%(asctime)-s] [%(levelname)-8s] %(name)s %(message)s ... ( %(filename)s:%(levelno)s )"
)
logger.setLevel(level)

if not logger.handlers:
if logger_type == LoggingType.CONSOLE:
if is_tty():
handler = ColorfulConsoleLoggerHandler()
else:
handler = logging.StreamHandler()
elif logger_type == LoggingType.FILE:
handler = logging.FileHandler("session.log", "a", encoding="utf-8")

handler.setFormatter(format)
logger.addHandler(handler)

return logger


if __name__ == "__main__":
logger = get_logger()
logger.debug("This is a DEBUG log.")
logger.info("This is a INFO log.")
logger.warning("This is a WARNING log.")
logger.critical("This is a CRITICAL log.")
logger.fatal("This is a FATAL log.")
Empty file.
19 changes: 19 additions & 0 deletions dysession/logger/handler/ansi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
from enum import Enum


class ANSIColor(Enum):
HEADER = "\033[95m"
OKBLUE = "\033[94m"
OKCYAN = "\033[96m"
OKGREEN = "\033[92m"
SUCCESSFUL = "\033[38;5;107m" # 7b9246
WARNING = "\033[93m"
FAIL = "\033[91m"
DEBUG = "\033[37m"
ENDC = "\033[0m"
BOLD = "\033[1m"
UNDERLINE = "\033[4m"


def colorful_it(color: ANSIColor, content: str) -> str:
return f"{color.value}{content}{ANSIColor.ENDC.value}"
37 changes: 37 additions & 0 deletions dysession/logger/handler/colorful_console.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import logging

from .ansi import ANSIColor

LOGLEVEL_TRANSFORM = {
logging.DEBUG: ANSIColor.DEBUG.value,
logging.INFO: ANSIColor.OKCYAN.value,
logging.WARNING: ANSIColor.WARNING.value,
logging.CRITICAL: ANSIColor.FAIL.value,
logging.FATAL: ANSIColor.FAIL.value,
}


class ColorfulConsoleLoggerHandler(logging.StreamHandler):
"""
A handler class which allows the cursor to stay on
one line for selected messages
"""

def emit(self, record):
try:
# record.msg = "QQQQQQQQQQQQQQ"
# record.levelname = "\033[91m" + record.levelname + "\033[0m"
record.levelname = (
LOGLEVEL_TRANSFORM[record.levelno]
+ f"{record.levelname:>8}"
+ ANSIColor.ENDC.value
)

msg = self.format(record)
self.stream.write(msg)
self.stream.write(self.terminator)
self.flush()
except (KeyboardInterrupt, SystemExit):
raise
except:
self.handleError(record)
4 changes: 4 additions & 0 deletions dysession/management/commands/dysession_init.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from django.core.management.base import BaseCommand, CommandParser

from dysession.aws.dynamodb import create_dynamodb_table
from dysession.logger import get_logger
from dysession.settings import get_config

from ._arg_types import positive_int
Expand Down Expand Up @@ -64,4 +65,7 @@ def add_arguments(self, parser: CommandParser) -> None:
return super().add_arguments(parser)

def handle(self, *args: Any, **options: Any) -> Optional[str]:
logger = get_logger()
logger.info("Start command: initialize dynamodb table")
create_dynamodb_table(options=options)
logger.info("End of command: dynamodb table created successfully!")

0 comments on commit 85e160c

Please sign in to comment.