Created
September 26, 2026 14:26
-
-
Save x-magic/2d1ddd5805bd7517c76403cbbeeb5116 to your computer and use it in GitHub Desktop.
Simple serial console logger with timestamps to use with screen
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python3 | |
| import sys | |
| import argparse | |
| import datetime | |
| import serial | |
| ## Initiate logging like: screen -d -m -S foobar ./logger.py -b 115200 -p foobar /dev/ttyACM1 | |
| ## Check command line options with ./logger.py -h | |
| ## Written with help from OpenAI Codex (GPT-5.6 Sol Medium) | |
| def main(): | |
| # Parse command line arguments | |
| parser = argparse.ArgumentParser( | |
| description="Serial Logger with Timestamps" | |
| ) | |
| parser.add_argument( | |
| "port", | |
| nargs="?", | |
| default="/dev/ttyUSB0", | |
| help="Serial port device (e.g. /dev/serial0, /dev/ttyUSB0, /dev/ttyACM0). Default: /dev/ttyUSB0" | |
| ) | |
| parser.add_argument( | |
| "-b", "--baud", | |
| type=int, | |
| default=115200, | |
| help="Baud rate (default: 115200)" | |
| ) | |
| parser.add_argument( | |
| "-p", "--prefix", | |
| default="logger", | |
| help="Log filename prefix (default: logger)" | |
| ) | |
| args = parser.parse_args() | |
| # Generate filename with starting timestamp | |
| start_time_str = datetime.datetime.now().strftime("%Y%m%d_%H%M%S") | |
| log_filename = f"{args.prefix}-{start_time_str}.log" | |
| print(f"[*] Opening serial port: {args.port} at {args.baud} baud") | |
| print(f"[*] Logging output to: {log_filename}") | |
| print("[*] Press Ctrl+C to stop logging.\n" + "-" * 50) | |
| try: | |
| # Open serial port | |
| ser = serial.Serial(args.port, args.baud, timeout=1) | |
| # Open log file in append mode with explicit line flushing | |
| with open(log_filename, "a", encoding="utf-8", errors="replace") as log_file: | |
| while True: | |
| # Read line from serial buffer | |
| raw_line = ser.readline() | |
| if raw_line: | |
| # Decode byte stream to string | |
| decoded_line = raw_line.decode"utf-8", errors="replace").rstrip("\r\n") | |
| if decoded_line: | |
| # Timestamp each line | |
| now_str = datetime.datetime.now().strftime("[%Y-%m-%d %H:%M:%S]") | |
| formatted_line = f"{now_str} {decoded_line}\n" | |
| # Print to screen | |
| sys.stdout.write(formatted_line) | |
| sys.stdout.flush() | |
| # Save to log file | |
| log_file.write(formatted_line) | |
| log_file.flush() | |
| except serial.SerialException as e: | |
| print(f"\n[!] Serial Error: {e}") | |
| sys.exit(1) | |
| except KeyboardInterrupt: | |
| print("\n[*] Logging stopped by user.") | |
| sys.exit(0) | |
| if __name__ == "__main__": | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment