79 lines
2.1 KiB
Python
79 lines
2.1 KiB
Python
import os
|
|
import sys
|
|
import threading
|
|
from typing import Optional
|
|
from datetime import datetime
|
|
from colorama import Fore, Style, init
|
|
|
|
if sys.platform == "win32":
|
|
try:
|
|
if hasattr(sys.stdout, "reconfigure"):
|
|
sys.stdout.reconfigure(encoding="utf-8")
|
|
if hasattr(sys.stderr, "reconfigure"):
|
|
sys.stderr.reconfigure(encoding="utf-8")
|
|
except Exception:
|
|
pass
|
|
|
|
init(autoreset=True)
|
|
|
|
_print_lock = threading.Lock()
|
|
_log_file: Optional[str] = None
|
|
|
|
|
|
def setup_logger(log_file_path: Optional[str] = None):
|
|
"""Настройка файла логирования для самого менеджера"""
|
|
global _log_file
|
|
if log_file_path:
|
|
os.makedirs(os.path.dirname(os.path.abspath(log_file_path)), exist_ok=True)
|
|
_log_file = log_file_path
|
|
|
|
|
|
def _format_msg(level_name: str, color: str, msg: str) -> str:
|
|
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
|
return f"{color}[{timestamp}] [{level_name}] {msg}{Style.RESET_ALL}"
|
|
|
|
|
|
def _write_to_file(level_name: str, msg: str):
|
|
if _log_file:
|
|
try:
|
|
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
|
with open(_log_file, "a", encoding="utf-8") as f:
|
|
f.write(f"[{timestamp}] [{level_name}] {msg}\n")
|
|
except Exception:
|
|
pass
|
|
|
|
|
|
def log_info(msg: str):
|
|
formatted = _format_msg("ИНФО", Fore.GREEN, msg)
|
|
with _print_lock:
|
|
print(formatted)
|
|
_write_to_file("ИНФО", msg)
|
|
|
|
|
|
def log_warn(msg: str):
|
|
formatted = _format_msg("ПРЕДУПРЕЖДЕНИЕ", Fore.YELLOW, msg)
|
|
with _print_lock:
|
|
print(formatted)
|
|
_write_to_file("ПРЕДУПРЕЖДЕНИЕ", msg)
|
|
|
|
|
|
def log_err(msg: str):
|
|
formatted = _format_msg("ОШИБКА", Fore.RED, msg)
|
|
with _print_lock:
|
|
print(formatted)
|
|
_write_to_file("ОШИБКА", msg)
|
|
|
|
|
|
def log_setup(msg: str):
|
|
formatted = _format_msg("SETUP", Fore.BLUE, msg)
|
|
with _print_lock:
|
|
print(formatted)
|
|
_write_to_file("SETUP", msg)
|
|
|
|
|
|
def log_debug(msg: str):
|
|
formatted = _format_msg("DEBUG", Fore.MAGENTA, msg)
|
|
with _print_lock:
|
|
print(formatted)
|
|
_write_to_file("DEBUG", msg)
|