76 lines
2.4 KiB
Python
76 lines
2.4 KiB
Python
"""
|
|
* SPDX-FileCopyrightText: 2023-2025 PeppermintOS Team
|
|
* (peppermintosteam@proton.me)
|
|
* SPDX-License-Identifier: GPL-3.0-or-later
|
|
*
|
|
* The logger modules used for the system wide logging
|
|
"""
|
|
|
|
import logging
|
|
from logging.handlers import RotatingFileHandler
|
|
import sys
|
|
from pathlib import Path
|
|
from python_modules.paths_modules import HOME_FOLDER
|
|
|
|
|
|
def supports_color():
|
|
"""Check if the system supports color output."""
|
|
return hasattr(sys.stdout, 'isatty') and sys.stdout.isatty()
|
|
|
|
|
|
def color_message(message, level):
|
|
"""Set the coloring for the logger messages."""
|
|
if not supports_color():
|
|
return message
|
|
level_colors = {
|
|
logging.DEBUG: '\033[94m', # Blue
|
|
logging.INFO: '\033[92m', # Green
|
|
logging.WARNING: '\033[93m', # Yellow
|
|
logging.ERROR: '\033[91m', # Red
|
|
logging.CRITICAL: '\033[95m', # Magenta
|
|
}
|
|
color = level_colors.get(level, '\033[0m')
|
|
return f"{color}{message}\033[0m"
|
|
|
|
|
|
def color_format(record):
|
|
"""Format the log record with color."""
|
|
message = record.getMessage()
|
|
return color_message(message, record.levelno)
|
|
|
|
|
|
def setup_logger(builder, log_filename='builder.log'):
|
|
"""
|
|
This will setup the logger as follows
|
|
- In the arguments set the log file name
|
|
- The Log file location "HOMEFOLDER"
|
|
- Logging level
|
|
- Console handler with color
|
|
- File handler (rotating) without color
|
|
"""
|
|
logger = logging.getLogger(builder)
|
|
logger.setLevel(logging.DEBUG)
|
|
console_handler = logging.StreamHandler()
|
|
console_handler.setLevel(logging.DEBUG)
|
|
console_handler.setFormatter(
|
|
logging.Formatter(
|
|
'%(asctime)s - %(name)s - %(levelname)s - %(message)s'
|
|
)
|
|
)
|
|
# Override the format method
|
|
console_handler.format = color_format
|
|
log_file = Path(HOME_FOLDER) / 'logs' / log_filename
|
|
# Ensure log directory exists
|
|
log_file.parent.mkdir(exist_ok=True)
|
|
file_handler = RotatingFileHandler(
|
|
log_file, maxBytes=1024*1024, backupCount=5)
|
|
file_handler.setLevel(logging.DEBUG)
|
|
file_handler.setFormatter(
|
|
logging.Formatter(
|
|
'%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
|
|
logger.addHandler(console_handler)
|
|
logger.addHandler(file_handler)
|
|
return logger
|
|
# Variables Arguments used for the logger setUp for all files.
|
|
builder_logger = setup_logger('builder', 'builder.log')
|