File size: 6,647 Bytes
9deebf2 | 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 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 | """
Errata logging system for tracking data quality issues.
The ErrataLogger captures detailed information about data problems
encountered during processing, enabling post-processing analysis
and data quality reporting.
"""
from pathlib import Path
from typing import Any, Dict, Optional
from datetime import datetime
import json
import logging
class ErrataLogger:
"""
Logs data quality issues and errors during processing.
Creates structured log files per dataset with detailed error
information including file paths, row numbers, error types,
and the problematic data.
"""
def __init__(
self,
log_dir: str | Path,
dataset_name: str,
max_errors: int = 1000
):
"""
Initialize errata logger for a dataset.
Args:
log_dir: Directory for errata log files
dataset_name: Name of the dataset being processed
max_errors: Maximum errors to log per file (prevents huge logs)
"""
self.log_dir = Path(log_dir)
self.log_dir.mkdir(parents=True, exist_ok=True)
# Create latest directory (for current logs, not gitignored)
self.latest_dir = self.log_dir.parent / 'latest'
self.latest_dir.mkdir(parents=True, exist_ok=True)
self.dataset_name = dataset_name
self.max_errors = max_errors
# Create timestamped log file (historical, gitignored)
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
self.log_file = self.log_dir / f"{dataset_name}_{timestamp}_errata.jsonl"
# Create latest log file (current, not gitignored)
self.latest_log_file = self.latest_dir / f"{dataset_name}_latest_errata.jsonl"
# Track error counts
self.error_counts: Dict[str, int] = {}
self.total_errors = 0
# Initialize log files with header
self._write_header()
def _write_header(self) -> None:
"""Write log file header with metadata."""
header = {
'type': 'header',
'dataset': self.dataset_name,
'timestamp': datetime.now().isoformat(),
'max_errors_per_file': self.max_errors
}
self._write_entry(header)
def _write_entry(self, entry: Dict[str, Any]) -> None:
"""Write a single log entry as JSON line to both timestamped and latest files."""
# Write to timestamped file (historical)
with open(self.log_file, 'a') as f:
f.write(json.dumps(entry) + '\n')
# Write to latest file (current)
with open(self.latest_log_file, 'a') as f:
f.write(json.dumps(entry) + '\n')
def log_error(
self,
error_type: str,
message: str,
file_path: Optional[str] = None,
row_number: Optional[int] = None,
line_number: Optional[int] = None,
row_data: Optional[Any] = None,
context: Optional[Dict[str, Any]] = None,
scope: str = 'row'
) -> None:
"""
Log a data quality error.
Args:
error_type: Type of error (e.g., 'encoding', 'validation', 'schema')
message: Human-readable error description
file_path: Path to the file with the error
row_number: Row number in the DataFrame (0-indexed)
line_number: Line number in the source file (1-indexed)
row_data: The problematic data row (if applicable)
context: Additional context information
scope: Error scope - 'file' (whole file omitted) or 'row' (single row omitted)
"""
# Check if we've exceeded max errors for this file
file_key = file_path or 'unknown'
if file_key in self.error_counts:
if self.error_counts[file_key] >= self.max_errors:
return
else:
self.error_counts[file_key] = 0
# Build log entry
entry = {
'type': 'error',
'error_type': error_type,
'message': message,
'scope': scope, # 'file' or 'row'
'timestamp': datetime.now().isoformat()
}
if file_path:
entry['file'] = file_path
if row_number is not None:
entry['row_number'] = row_number
if line_number is not None:
entry['line_number'] = line_number
if row_data is not None:
# Convert to string to ensure JSON serializable
entry['row_data'] = str(row_data)
if context:
entry['context'] = context
self._write_entry(entry)
self.error_counts[file_key] += 1
self.total_errors += 1
def log_file_summary(
self,
file_path: str,
status: str,
rows_processed: int,
rows_valid: int,
rows_invalid: int
) -> None:
"""
Log summary statistics for a processed file.
Args:
file_path: Path to the processed file
status: Processing status ('success', 'partial', 'failed')
rows_processed: Total rows attempted
rows_valid: Number of valid rows
rows_invalid: Number of invalid rows
"""
entry = {
'type': 'file_summary',
'file': file_path,
'status': status,
'rows_processed': rows_processed,
'rows_valid': rows_valid,
'rows_invalid': rows_invalid,
'timestamp': datetime.now().isoformat()
}
self._write_entry(entry)
def get_summary(self) -> Dict[str, Any]:
"""
Get summary of all logged errors.
Returns:
Dictionary with error counts and statistics
"""
error_types = {}
files_with_errors = len(self.error_counts)
# Count errors by type by re-reading log file
with open(self.log_file, 'r') as f:
for line in f:
entry = json.loads(line)
if entry.get('type') == 'error':
error_type = entry.get('error_type', 'unknown')
error_types[error_type] = error_types.get(error_type, 0) + 1
return {
'total_errors': self.total_errors,
'files_with_errors': files_with_errors,
'error_types': error_types,
'log_file': str(self.log_file)
}
def close(self) -> None:
"""Close the logger and write final summary."""
footer = {
'type': 'footer',
'summary': self.get_summary(),
'timestamp': datetime.now().isoformat()
}
self._write_entry(footer) |