|
| 1 | +r""" |
| 2 | +================================================================================ |
| 3 | +Logger Utility Module |
| 4 | +================================================================================ |
| 5 | +Author : Breno Farias da Silva |
| 6 | +Created : 2025-12-11 |
| 7 | +Description : |
| 8 | + Dual-channel logger that mirrors console output to both the terminal |
| 9 | + (preserving ANSI color sequences when the terminal is a TTY) and a |
| 10 | + sanitized log file (ANSI sequences removed). Designed for use in |
| 11 | + interactive sessions, background jobs, CI pipelines and Makefile runs. |
| 12 | +
|
| 13 | + Behavior: |
| 14 | + - When attached to `sys.stdout`/`sys.stderr` the logger writes colored |
| 15 | + output to the controlling terminal (when available) and a color-free |
| 16 | + record to the specified log file. |
| 17 | + - ANSI escape sequences are removed from the file output using a |
| 18 | + conservative regex; lines are flushed immediately to keep logs live. |
| 19 | + - Provides minimal API: `write()`, `flush()` and `close()` so it can be |
| 20 | + used as a drop-in replacement for `sys.stdout`. |
| 21 | +
|
| 22 | +Usage: |
| 23 | + from Logger import Logger |
| 24 | + logger = Logger("./Logs/myrun.log", clean=True) |
| 25 | + sys.stdout = logger # optional: redirect all prints to logger |
| 26 | +
|
| 27 | +Notes & TODOs: |
| 28 | + - Consider adding timestamps, log rotation, and JSON output format. |
| 29 | + - The ANSI regex is intentionally simple; adjust if you need broader support. |
| 30 | +
|
| 31 | +Dependencies: |
| 32 | + - Python >= 3.8 (no external runtime dependencies required) |
| 33 | +
|
| 34 | +Assumptions: |
| 35 | + - The log file will contain cleaned, human-readable text (no ANSI codes). |
| 36 | + - The logger is safe for short-lived scripts and long-running processes. |
| 37 | +""" |
| 38 | + |
| 39 | +import os # For interacting with the filesystem |
| 40 | +import re # For stripping ANSI escape sequences |
| 41 | +import sys # For replacing stdout/stderr |
| 42 | + |
| 43 | +# Regex Constants: |
| 44 | +ANSI_ESCAPE_REGEX = re.compile(r"\x1B\[[0-9;]*[a-zA-Z]") # Pattern to remove ANSI colors |
| 45 | + |
| 46 | +# Classes Definitions: |
| 47 | + |
| 48 | + |
| 49 | +class Logger: |
| 50 | + """ |
| 51 | + Simple logger class that prints colored messages to the terminal and |
| 52 | + writes a cleaned (ANSI-stripped) version to a log file. |
| 53 | +
|
| 54 | + Usage: |
| 55 | + logger = Logger("./Logs/output.log", clean=True) |
| 56 | + logger.info("\x1b[92mHello world\x1b[0m") |
| 57 | +
|
| 58 | + :param logfile_path: Path to the log file. |
| 59 | + :param clean: If True, truncate the log file on init; otherwise append. |
| 60 | + """ |
| 61 | + |
| 62 | + def __init__(self, logfile_path, clean=False): |
| 63 | + """ |
| 64 | + Initialize the Logger. |
| 65 | +
|
| 66 | + :param self: Instance of the Logger class. |
| 67 | + :param logfile_path: Path to the log file. |
| 68 | + :param clean: If True, truncate the log file on init; otherwise append. |
| 69 | + """ |
| 70 | + |
| 71 | + self.logfile_path = logfile_path # Store log file path |
| 72 | + |
| 73 | + parent = os.path.dirname(logfile_path) # Ensure log directory exists |
| 74 | + if parent and not os.path.exists(parent): # Create parent directories if needed |
| 75 | + os.makedirs(parent, exist_ok=True) # Safe creation |
| 76 | + |
| 77 | + mode = "w" if clean else "a" # Choose file mode based on 'clean' flag |
| 78 | + self.logfile = open(logfile_path, mode, encoding="utf-8") # Open log file |
| 79 | + self.is_tty = sys.stdout.isatty() # Verify if stdout is a TTY |
| 80 | + |
| 81 | + def write(self, message): |
| 82 | + """ |
| 83 | + Internal method to write messages to both terminal and log file. |
| 84 | +
|
| 85 | + :param self: Instance of the Logger class. |
| 86 | + :param message: The message to log. |
| 87 | + """ |
| 88 | + |
| 89 | + if message is None: # Ignore None messages |
| 90 | + return # Early exit |
| 91 | + |
| 92 | + out = str(message) # Convert message to string |
| 93 | + if not out.endswith("\n"): # Ensure newline termination |
| 94 | + out += "\n" # Append newline if missing |
| 95 | + |
| 96 | + clean_out = ANSI_ESCAPE_REGEX.sub("", out) # Strip ANSI sequences for log file |
| 97 | + |
| 98 | + try: # Write to log file |
| 99 | + self.logfile.write(clean_out) # Write cleaned message |
| 100 | + self.logfile.flush() # Ensure immediate write |
| 101 | + except Exception: # Fail silently to avoid breaking user code |
| 102 | + pass # Silent fail |
| 103 | + |
| 104 | + try: # Write to terminal: colored when TTY, cleaned otherwise |
| 105 | + if sys.__stdout__ is not None: |
| 106 | + if self.is_tty: # Terminal supports colors |
| 107 | + sys.__stdout__.write(out) # Write colored message |
| 108 | + sys.__stdout__.flush() # Flush immediately |
| 109 | + else: # Terminal does not support colors |
| 110 | + sys.__stdout__.write(clean_out) # Write cleaned message |
| 111 | + sys.__stdout__.flush() # Flush immediately |
| 112 | + except Exception: # Fail silently to avoid breaking user code |
| 113 | + pass # Silent fail |
| 114 | + |
| 115 | + def flush(self): |
| 116 | + """ |
| 117 | + Flush the log file. |
| 118 | +
|
| 119 | + :param self: Instance of the Logger class. |
| 120 | + """ |
| 121 | + |
| 122 | + try: # Flush log file buffer |
| 123 | + self.logfile.flush() # Flush log file |
| 124 | + except Exception: # Fail silently |
| 125 | + pass # Silent fail |
| 126 | + |
| 127 | + def close(self): |
| 128 | + """ |
| 129 | + Close the log file. |
| 130 | +
|
| 131 | + :param self: Instance of the Logger class. |
| 132 | + """ |
| 133 | + |
| 134 | + try: # Close log file |
| 135 | + self.logfile.close() # Close log file |
| 136 | + except Exception: # Fail silently |
| 137 | + pass # Silent fail |
0 commit comments