59 lines
2.6 KiB
Python
59 lines
2.6 KiB
Python
import logging
|
|
import sys
|
|
import os
|
|
import datetime
|
|
|
|
def setup_logging():
|
|
"""Konfiguruje zaawansowane logowanie z dwoma handlerami i czyszczeniem starych logów."""
|
|
# 1. Pobierz główny logger, wyczyść istniejące handlery i ustaw najniższy poziom (DEBUG)
|
|
logger = logging.getLogger()
|
|
if logger.hasHandlers():
|
|
logger.handlers.clear()
|
|
logger.setLevel(logging.DEBUG)
|
|
|
|
# 2. Utwórz katalog 'logs', jeśli nie istnieje
|
|
LOGS_DIR = "logs"
|
|
if not os.path.exists(LOGS_DIR):
|
|
os.makedirs(LOGS_DIR)
|
|
|
|
# 3. Stwórz i skonfiguruj handler dla konsoli (poziom INFO)
|
|
console_handler = logging.StreamHandler(sys.stdout)
|
|
console_handler.setLevel(logging.INFO)
|
|
console_formatter = logging.Formatter('%(levelname)s - %(message)s')
|
|
console_handler.setFormatter(console_formatter)
|
|
logger.addHandler(console_handler)
|
|
|
|
# 4. Stwórz i skonfiguruj handler dla pliku (poziom DEBUG)
|
|
log_filename = datetime.datetime.now().strftime("debug_%Y-%m-%d_%H-%M-%S.log")
|
|
file_handler = logging.FileHandler(os.path.join(LOGS_DIR, log_filename))
|
|
file_handler.setLevel(logging.DEBUG)
|
|
file_formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
|
|
file_handler.setFormatter(file_formatter)
|
|
logger.addHandler(file_handler)
|
|
|
|
def cleanup_old_logs(log_dir="logs", retention_days=7):
|
|
"""Usuwa pliki logów starsze niż określona liczba dni."""
|
|
logging.info(f"Rozpoczynam czyszczenie starych logów (starszych niż {retention_days} dni)...")
|
|
try:
|
|
now = datetime.datetime.now()
|
|
cutoff = now - datetime.timedelta(days=retention_days)
|
|
files_deleted = 0
|
|
for filename in os.listdir(log_dir):
|
|
file_path = os.path.join(log_dir, filename)
|
|
# Upewnij się, że to plik i nie jest to aktualnie otwarty plik logu
|
|
if os.path.isfile(file_path) and filename != os.path.basename(file_handler.baseFilename):
|
|
file_mod_time = datetime.datetime.fromtimestamp(os.path.getmtime(file_path))
|
|
if file_mod_time < cutoff:
|
|
os.remove(file_path)
|
|
files_deleted += 1
|
|
logging.info(f"Usunięto stary plik logu: {filename}")
|
|
if files_deleted == 0:
|
|
logging.info("Nie znaleziono starych logów do usunięcia.")
|
|
except Exception as e:
|
|
logging.warning(f"Wystąpił błąd podczas czyszczenia starych logów: {e}")
|
|
|
|
# 5. Uruchom funkcję czyszczącą
|
|
cleanup_old_logs(LOGS_DIR)
|
|
|
|
logging.info("Logging został skonfigurowany.")
|