File size: 6,132 Bytes
9720daa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
"""
Centralized logging utilities for Reddit mod collection pipeline.
Simple unified logger that works for both main process and multiprocessing.
"""

import logging
import multiprocessing
import os
import re
from datetime import datetime
from pathlib import Path
from utils.files import ensure_directory


def setup_stage_logger(stage_name: str, log_level: str = "INFO", worker_identifier: str = None) -> logging.Logger:
    """
    Set up a unified logger for a pipeline stage that works with multiprocessing.
    Creates stage-specific directories and separate logs for main vs worker processes.

    Args:
        stage_name: Name of the stage (e.g., "stage1_collect_mod_comments")
        log_level: Logging level (DEBUG, INFO, WARNING, ERROR)
        worker_identifier: Meaningful name for worker (e.g., "RC_2023-02", "askreddit").
                          If provided, creates worker log; if None, creates main log.

    Returns:
        Configured logger instance that works in both main and worker processes
    """
    from config import PATHS

    # Extract stage number from stage_name (e.g., "stage1_collect_mod_comments" -> "1")
    stage_match = re.match(r'stage(\d+)_', stage_name)
    stage_num = stage_match.group(1) if stage_match else "unknown"

    # Create stage-specific log directory using full stage name
    base_log_dir = Path(PATHS['logs'])
    stage_log_dir = base_log_dir / stage_name
    stage_log_dir.mkdir(parents=True, exist_ok=True)

    # Create timestamp for log file
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")

    # Simple naming for main vs worker processes
    if worker_identifier:
        # Use meaningful worker identifier (e.g., "RC_2023-02", "askreddit", "subreddits/askreddit")
        log_file = stage_log_dir / f"{worker_identifier}_{timestamp}.log"
        # Ensure parent directory exists for the log file (handles subdirectories in worker_identifier)
        ensure_directory(str(log_file))
    else:
        log_file = stage_log_dir / f"main_{timestamp}.log"

    # Create logger with process-safe name
    if worker_identifier:
        logger_name = f"{stage_name}_{worker_identifier}"
    else:
        logger_name = f"{stage_name}_main"
    logger = logging.getLogger(logger_name)
    logger.setLevel(getattr(logging, log_level.upper()))

    # Clear any existing handlers to avoid duplicates
    logger.handlers.clear()

    # Create formatters with process info
    file_formatter = logging.Formatter(
        '%(asctime)s - PID:%(process)d - %(levelname)s - %(message)s',
        datefmt='%Y-%m-%d %H:%M:%S'
    )

    console_formatter = logging.Formatter(
        'PID:%(process)d - %(levelname)s - %(message)s'
    )

    # Thread-safe file handler (multiple processes can write to same file)
    file_handler = logging.FileHandler(log_file, encoding='utf-8')
    file_handler.setLevel(logging.DEBUG)  # Log everything to file
    file_handler.setFormatter(file_formatter)

    # Note: Using default file handler locking for multiprocessing safety
    logger.addHandler(file_handler)

    # Console handler (for real-time feedback)
    console_handler = logging.StreamHandler()
    console_handler.setLevel(getattr(logging, log_level.upper()))
    console_handler.setFormatter(console_formatter)
    logger.addHandler(console_handler)

    # Log the initialization
    if worker_identifier:
        logger.info(f"Worker logger initialized for {stage_name} ({worker_identifier})")
    else:
        logger.info(f"Main logger initialized for {stage_name}")
    logger.info(f"Log file: {log_file}")

    return logger


def get_stage_logger(stage_num: int, stage_description: str = None, worker_identifier: str = None) -> logging.Logger:
    """
    Get a logger for a specific stage number.

    Args:
        stage_num: Stage number (0-9)
        stage_description: Optional description for the stage
        worker_identifier: Meaningful name for worker (e.g., "RC_2023-02", "askreddit").
                          If provided, creates worker log; if None, creates main log.

    Returns:
        Configured logger instance
    """
    if stage_description:
        stage_name = f"stage{stage_num}_{stage_description}"
    else:
        stage_name = f"stage{stage_num}"

    return setup_stage_logger(stage_name, worker_identifier=worker_identifier)


def log_stage_start(logger: logging.Logger, stage_num: int, stage_name: str):
    """Log the start of a pipeline stage."""
    logger.info("=" * 60)
    logger.info(f"🚀 Stage {stage_num}: {stage_name}")
    logger.info("=" * 60)


def log_stage_end(logger: logging.Logger, stage_num: int, success: bool = True, elapsed_time: float = None):
    """Log the end of a pipeline stage."""
    status = "✅ COMPLETED" if success else "❌ FAILED"
    time_str = f" in {elapsed_time:.1f}s" if elapsed_time else ""
    logger.info(f"{status}: Stage {stage_num}{time_str}")
    logger.info("=" * 60)


def log_progress(logger: logging.Logger, current: int, total: int, item_name: str = "items"):
    """Log progress with percentage."""
    percentage = (current / total) * 100 if total > 0 else 0
    logger.info(f"📊 Progress: {current:,}/{total:,} {item_name} ({percentage:.1f}%)")


def log_stats(logger: logging.Logger, stats_dict: dict, title: str = "Statistics"):
    """Log statistics in a formatted way."""
    logger.info(f"📈 {title}:")
    for key, value in stats_dict.items():
        if isinstance(value, (int, float)):
            logger.info(f"  {key}: {value:,}")
        else:
            logger.info(f"  {key}: {value}")


def log_error_and_continue(logger: logging.Logger, error: Exception, context: str = ""):
    """Log an error but continue processing."""
    context_str = f" in {context}" if context else ""
    logger.error(f"❌ Error{context_str}: {str(error)}")
    logger.debug(f"Full traceback{context_str}:", exc_info=True)


def log_file_operation(logger: logging.Logger, operation: str, file_path: str, success: bool = True):
    """Log file operations (read, write, etc.)."""
    status = "✅" if success else "❌"
    logger.debug(f"{status} {operation}: {file_path}")