Coverage for little_loops / logger.py: 100%
49 statements
« prev ^ index » next coverage.py v7.12.0, created at 2026-03-04 01:17 -0600
« prev ^ index » next coverage.py v7.12.0, created at 2026-03-04 01:17 -0600
1"""Logging utilities for little-loops.
3Provides colorized console output with timestamps for automation tools.
4"""
6from __future__ import annotations
8import sys
9from datetime import datetime
12class Logger:
13 """Simple logger with timestamps and colors.
15 Provides info, success, warning, and error logging methods with
16 optional colorized output for terminal display.
18 Attributes:
19 verbose: Whether to output messages (False silences all output)
20 use_color: Whether to use ANSI color codes
21 """
23 # ANSI color codes
24 CYAN = "\033[36m"
25 GREEN = "\033[32m"
26 YELLOW = "\033[33m"
27 RED = "\033[31m"
28 MAGENTA = "\033[35m"
29 GRAY = "\033[90m"
30 RESET = "\033[0m"
32 def __init__(self, verbose: bool = True, use_color: bool = True) -> None:
33 """Initialize logger.
35 Args:
36 verbose: Whether to output messages
37 use_color: Whether to use ANSI color codes
38 """
39 self.verbose = verbose
40 self.use_color = use_color
42 def _timestamp(self) -> str:
43 """Get current timestamp string."""
44 return datetime.now().strftime("%H:%M:%S")
46 def _format(self, color: str, msg: str) -> str:
47 """Format message with timestamp and optional color."""
48 ts = self._timestamp()
49 if self.use_color:
50 return f"{color}[{ts}]{self.RESET} {msg}"
51 return f"[{ts}] {msg}"
53 def info(self, msg: str) -> None:
54 """Log an info message."""
55 if self.verbose:
56 print(self._format(self.CYAN, msg))
58 def debug(self, msg: str) -> None:
59 """Log a debug message (gray/dim)."""
60 if self.verbose:
61 print(self._format(self.GRAY, msg))
63 def success(self, msg: str) -> None:
64 """Log a success message."""
65 if self.verbose:
66 print(self._format(self.GREEN, msg))
68 def warning(self, msg: str) -> None:
69 """Log a warning message."""
70 if self.verbose:
71 print(self._format(self.YELLOW, msg))
73 def error(self, msg: str) -> None:
74 """Log an error message to stderr."""
75 if self.verbose:
76 print(self._format(self.RED, msg), file=sys.stderr)
78 def timing(self, msg: str) -> None:
79 """Log timing information."""
80 if self.verbose:
81 print(self._format(self.MAGENTA, msg))
83 def header(self, msg: str, char: str = "=", width: int = 60) -> None:
84 """Log a header with separators."""
85 if self.verbose:
86 line = char * width
87 print(line)
88 print(msg)
89 print(line)
92def format_duration(seconds: float) -> str:
93 """Format duration in human-readable form.
95 Args:
96 seconds: Duration in seconds
98 Returns:
99 Human-readable string like "5.2 seconds" or "3.5 minutes"
100 """
101 if seconds >= 60:
102 return f"{seconds / 60:.1f} minutes"
103 return f"{seconds:.1f} seconds"