Skip to content

Commit

Permalink
remade logging - completed
Browse files Browse the repository at this point in the history
  • Loading branch information
DefinetlyNotAI committed Sep 29, 2024
1 parent 102387c commit 822b6de
Showing 1 changed file with 39 additions and 43 deletions.
82 changes: 39 additions & 43 deletions log.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,10 @@
# log.py
import inspect
import os
from datetime import datetime
import colorlog
import logging

# TODO redo the log class of both logicytics and algopy to make it easier to setup and use,
# make it less janky
# Set up using a dictionary, and then use the dictionary to set up the logger,
# and then use the debug logger to log the dictionary )

# The available color names are:
#
# black
Expand All @@ -31,13 +27,6 @@
# light_white


# Define custom log levels
EXCEPTION_LOG_LEVEL = 45
INTERNAL_LOG_LEVEL = 5

logging.addLevelName(EXCEPTION_LOG_LEVEL, "EXCEPTION")
logging.addLevelName(INTERNAL_LOG_LEVEL, "INTERNAL")

class Log:
def __init__(self, config: dict = None):
config = config or {
Expand All @@ -50,11 +39,12 @@ def __init__(self, config: dict = None):
"error_color": "red",
"critical_color": "red",
"exception_color": "red",
"internal_color": "blue",
"colorlog_fmt_parameters": "%(log_color)s%(levelname)-8s%(reset)s %(blue)s%(message)s",
}

self.debug_bool = config.get("log_level", "INFO").upper() == "DEBUG"
self.EXCEPTION_LOG_LEVEL = 45
self.INTERNAL_LOG_LEVEL = 15
logging.addLevelName(self.EXCEPTION_LOG_LEVEL, "EXCEPTION")
logging.addLevelName(self.INTERNAL_LOG_LEVEL, "INTERNAL")
self.color = config.get("use_colorlog", True)
self.filename = config.get("filename", "AlgoPy.log")
if self.color:
Expand All @@ -64,7 +54,7 @@ def __init__(self, config: dict = None):
)
handler = colorlog.StreamHandler()
log_colors = {
"INTERNAL": config.get("internal_color", "blue"),
"INTERNAL": "cyan",
"DEBUG": config.get("debug_color", "cyan"),
"INFO": config.get("info_color", "green"),
"WARNING": config.get("warning_color", "yellow"),
Expand All @@ -80,7 +70,10 @@ def __init__(self, config: dict = None):

handler.setFormatter(formatter)
logger.addHandler(handler)
getattr(logging, config["log_level"].upper(), self.warning(f"Log Level {config['log_level']} not found, setting default level to INFO"))
try:
getattr(logging, config["log_level"].upper())
except AttributeError as AE:
self.__internal(f"Log Level {config['log_level']} not found, setting default level to INFO -> {AE}")

if not os.path.exists(self.filename):
self.newline()
Expand All @@ -92,69 +85,72 @@ def __timestamp() -> str:
return datetime.now().strftime('%Y-%m-%d %H:%M:%S')

@staticmethod
def __pad_message(message):
def __pad_message(message: str) -> str:
return (message + " " * (153 - len(message)) if len(message) < 153 else message[:150] + "...") + "|"

def raw(self, message):
def raw(self, message: str):
frame = inspect.stack()[1]
if frame.function == "<module>":
self.__internal(f"Raw message called from a non-function - This is not recommended")
with open(self.filename, "a") as f:
f.write(f"{message}\n")

def newline(self):
with open(self.filename, "a") as f:
f.write("|" + "-" * 19 + "|" + "-" * 13 + "|" + "-" * 154 + "|")
f.write("|" + "-" * 19 + "|" + "-" * 13 + "|" + "-" * 154 + "|" + "\n")

def info(self, message):
def info(self, message: str):
if self.color:
colorlog.info(message)
self.raw(f"[{self.__timestamp()}] > INFO: | {self.__pad_message(message)}\n")
self.raw(f"[{self.__timestamp()}] > INFO: | {self.__pad_message(message)}")

def warning(self, message):
def warning(self, message: str):
if self.color:
colorlog.warning(message)
self.raw(f"[{self.__timestamp()}] > WARNING: | {self.__pad_message(message)}\n")
self.raw(f"[{self.__timestamp()}] > WARNING: | {self.__pad_message(message)}")

def error(self, message):
def error(self, message: str):
if self.color:
colorlog.error(message)
self.raw(f"[{self.__timestamp()}] > ERROR: | {self.__pad_message(message)}\n")
self.raw(f"[{self.__timestamp()}] > ERROR: | {self.__pad_message(message)}")

def critical(self, message):
def critical(self, message: str):
if self.color:
colorlog.critical(message)
self.raw(f"[{self.__timestamp()}] > CRITICAL: | {self.__pad_message(message)}\n")
self.raw(f"[{self.__timestamp()}] > CRITICAL: | {self.__pad_message(message)}")

def debug(self, message):
def debug(self, message: str):
if message == "*-*":
self.raw("|" + "-" * 19 + "|" + "-" * 13 + "|" + "-" * 152 + "|")
else:
colorlog.debug(message)

def string(self, Message: str, Type: str):
def string(self, message: str, Type: str):
type_map = {"err": "error", "warn": "warning", "crit": "critical"}
Type = type_map.get(Type.lower(), Type)
try:
getattr(self, Type.lower())(Message)
getattr(self, Type.lower())(message)
except AttributeError as AE:
self.warning(f"A wrong Log Type was called: {Type} not found. -> {AE}")
getattr(self, "Debug".lower())(Message)
self.__internal(f"A wrong Log Type was called: {Type} not found. -> {AE}")
getattr(self, "Debug".lower())(message)

def exception(self, message):
def exception(self, message: str):
if self.color:
colorlog.log(EXCEPTION_LOG_LEVEL, message)
self.raw(f"[{self.__timestamp()}] > EXCEPTION:| {self.__pad_message(message)}\n")
colorlog.log(self.EXCEPTION_LOG_LEVEL, message)
self.raw(f"[{self.__timestamp()}] > EXCEPTION:| {self.__pad_message(message)}")

def __internal(self, message: str):
if self.color:
colorlog.log(self.INTERNAL_LOG_LEVEL, message)

def internal(self, message):
if self.color and self.debug_bool:
colorlog.log(INTERNAL_LOG_LEVEL, message)

config = {"log_level": "DEBUG"}
config = {"log_level": "debug"}
log = Log(config=config)
log.debug("This is a debug message")
log.error("This is an error message")
log.info("This is an info message")
log.warning("This is a warning message")
log.error("This is an error message")
log.critical("This is a critical message")
log.raw("This is a raw message")
log.string("This is log message from a string", "warn")
log.string("This is a log message from a string", "warn")
log.exception("This is an exception message")
log.internal("This is an internal message")

0 comments on commit 822b6de

Please sign in to comment.