File size: 1,152 Bytes
8e0b458
 
 
 
 
 
09c9920
8e0b458
09c9920
8e0b458
09c9920
 
 
 
 
 
 
 
 
 
 
 
 
 
8e0b458
 
 
09c9920
 
8e0b458
09c9920
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# utils/logger.py

import logging
import os
from datetime import datetime

def setup_logger(log_dir="logs", log_level=logging.INFO, enable_file_logging=True):
    """
    Sets up a logger that writes to console and optionally to a timestamped log file.
    """
    handlers = [logging.StreamHandler()]  # Always log to console
    
    if enable_file_logging:
        try:
            os.makedirs(log_dir, exist_ok=True)
            timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
            log_file = os.path.join(log_dir, f"log_{timestamp}.log")
            handlers.append(logging.FileHandler(log_file))
            print(f"File logging enabled: {log_file}")
        except PermissionError:
            print("File logging disabled due to permission issues - logging to console only")
        except Exception as e:
            print(f"File logging disabled due to error: {e}")
    
    logging.basicConfig(
        level=log_level,
        format="%(asctime)s [%(levelname)s] - %(message)s",
        handlers=handlers,
        force=True  # This ensures reconfiguration if already configured
    )
    logging.info("Logger initialized.")