Refactor logger setup and path handling

Moved sys.path modification from canvas_node.py to __init__.py for better package management. Improved logger formatting for colored output and enhanced file logging configuration with error handling for log directory creation. Added python/__init__.py to make the 'python' directory a package.
This commit is contained in:
Dariusz L
2025-06-28 01:26:33 +02:00
parent 375ed6a2b8
commit d8ebbeea1e
4 changed files with 45 additions and 18 deletions

View File

@@ -1,3 +1,9 @@
import sys
import os
# Add the custom node's directory to the Python path
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from .canvas_node import CanvasNode
CanvasNode.setup_routes()
@@ -12,4 +18,4 @@ NODE_DISPLAY_NAME_MAPPINGS = {
WEB_DIRECTORY = "./js"
__all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS", "WEB_DIRECTORY"]
__all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS", "WEB_DIRECTORY"]

View File

@@ -21,8 +21,6 @@ import io
import sys
import os
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'python'))
try:
from python.logger import logger, LogLevel, debug, info, warn, error, exception
@@ -242,8 +240,6 @@ class CanvasNode:
def process_canvas_image(self, trigger, output_switch, cache_enabled, node_id, prompt=None, unique_id=None, input_image=None,
input_mask=None):
log_info(f"[CanvasNode] 🔍 process_canvas_image wejście node_id={node_id!r}, unique_id={unique_id!r}, trigger={trigger}, output_switch={output_switch}")
try:
if not self.__class__._processing_lock.acquire(blocking=False):

4
python/__init__.py Normal file
View File

@@ -0,0 +1,4 @@
# This file makes the 'python' directory a package.
from . import logger
__all__ = ['logger']

View File

@@ -64,16 +64,28 @@ class ColoredFormatter(logging.Formatter):
self.use_colors = use_colors
def format(self, record):
# Get the formatted message from the record
message = record.getMessage()
if record.exc_info:
message += "\n" + self.formatException(record.exc_info)
levelname = record.levelname
message = super().format(record)
# Build the log prefix
prefix = '[{}] [{}] [{}]'.format(
self.formatTime(record, self.datefmt),
record.name,
record.levelname
)
# Apply color and bold styling to the prefix
if self.use_colors and hasattr(LogLevel, levelname):
level = getattr(LogLevel, levelname)
color = COLORS.get(level, '')
reset = COLORS['RESET']
return f"{color}{message}{reset}"
return message
level_enum = getattr(LogLevel, levelname)
if level_enum in COLORS:
# Apply bold (\033[1m) and color, then reset
prefix = f"\033[1m{COLORS[level_enum]}{prefix}{COLORS['RESET']}"
return f"{prefix} {message}"
class LayerForgeLogger:
"""Główna klasa loggera dla LayerForge"""
@@ -97,10 +109,6 @@ class LayerForgeLogger:
# Załaduj konfigurację ze zmiennych środowiskowych
self._load_config_from_env()
# Utwórz katalog logów, jeśli nie istnieje
if self.config['log_to_file']:
os.makedirs(self.config['log_dir'], exist_ok=True)
self._initialized = True
def _load_config_from_env(self):
@@ -147,6 +155,18 @@ class LayerForgeLogger:
def configure(self, config):
"""Konfiguracja loggera"""
self.config.update(config)
# Jeśli włączono logowanie do pliku, upewnij się, że katalog istnieje
if self.config.get('log_to_file') and self.config.get('log_dir'):
try:
os.makedirs(self.config['log_dir'], exist_ok=True)
except OSError as e:
# To jest sytuacja krytyczna, więc użyjmy print
print(f"[CRITICAL] Could not create log directory: {self.config['log_dir']}. Error: {e}")
traceback.print_exc()
# Wyłącz logowanie do pliku, aby uniknąć dalszych błędów
self.config['log_to_file'] = False
return self
def set_enabled(self, enabled):
@@ -202,7 +222,8 @@ class LayerForgeLogger:
file_handler = RotatingFileHandler(
log_file,
maxBytes=self.config['max_file_size_mb'] * 1024 * 1024,
backupCount=self.config['backup_count']
backupCount=self.config['backup_count'],
encoding='utf-8'
)
file_formatter = logging.Formatter(
fmt='[%(asctime)s] [%(name)s] [%(levelname)s] %(message)s',
@@ -296,4 +317,4 @@ def set_file_logging(enabled=True, log_dir=None):
# Zresetuj loggery, aby zastosować nowe ustawienia
logger.loggers = {}
return logger
return logger