Files
pyboot/pyapp/utils/log.py
2025-09-04 14:14:49 +08:00

113 lines
3.2 KiB
Python

import time
import json
from pyapp.status import status_manager
from pyapp.namespace import LogType
class Log:
MAX_TITLE_LENGTH:int = 7
TYPE_COLOR_MAP = {
LogType.INFO: "\033[94m",
LogType.ERROR: "\033[91m",
LogType.WARNING: "\033[93m",
LogType.SUCCESS: "\033[92m",
LogType.DEBUG: "\033[95m",
LogType.TERMINATE: "\033[96m"
}
@staticmethod
def get_time():
return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
@staticmethod
def blue(message):
# blue
print(f"\033[94m{message}\033[0m")
@staticmethod
def red(message):
# red
print(f"\033[91m{message}\033[0m")
@staticmethod
def yellow(message):
# yellow
print(f"\033[93m{message}\033[0m")
@staticmethod
def green(message):
# green
print(f"\033[92m{message}\033[0m")
@staticmethod
def log(message, log_type: str):
time_str = Log.get_time()
space = ""
if len(log_type) < Log.MAX_TITLE_LENGTH:
space = " " * (Log.MAX_TITLE_LENGTH - len(log_type))
if isinstance(message, dict):
formatted_message = json.dumps(message, indent=2, ensure_ascii=False)
else:
formatted_message = message
print (f"\033[1m\033[4m({time_str})\033[0m \033[1m{Log.TYPE_COLOR_MAP[log_type]}[{log_type.capitalize()}]\033[0m{space} {Log.TYPE_COLOR_MAP[log_type]}{formatted_message}\033[0m")
status_manager.add_log(time_str, log_type, formatted_message)
@staticmethod
def bold(message):
print(f"\033[1m{message}\033[0m")
@staticmethod
def underline(message):
print(f"\033[4m{message}\033[0m")
@staticmethod
def info(message):
Log.log(message, LogType.INFO)
@staticmethod
def error(message, terminate=False):
Log.log(message, LogType.ERROR)
if terminate:
Log.terminate("Application Terminated.")
@staticmethod
def warning(message):
Log.log(message, LogType.WARNING)
@staticmethod
def success(message):
Log.log(message, LogType.SUCCESS)
@staticmethod
def debug(message):
Log.log(message, LogType.DEBUG)
@staticmethod
def terminate(message):
Log.log(message, LogType.TERMINATE)
exit(1)
if __name__ == "__main__":
Log.info("This is a info message")
Log.error("This is a error message")
Log.warning("This is a warning message")
Log.success("This is a success message")
Log.debug("This is a debug message")
Log.blue("This is a blue message")
Log.red("This is a red message")
Log.yellow("This is a yellow message")
Log.green("This is a green message")
Log.bold("This is a bold message")
Log.underline("This is a underline message")
test_dict = {
"name": "John Doe",
"age": 25,
"city": "New York",
"hobbies": ["reading", "swimming", "programming"],
"address": {
"street": "Main Street",
"number": 123
}
}
Log.info("Dictionary test:")
Log.info(test_dict)