#!/usr/bin/env python3
"""
IRIS Bot Log Viewer Script
View and manage bot logs
"""
import sys
import subprocess
import argparse
from pathlib import Path
# Add project root to path
PROJECT_ROOT = Path(__file__).parent.parent
sys.path.insert(0, str(PROJECT_ROOT))
# Colors
class Colors:
RED = '\033[0;31m'
GREEN = '\033[0;32m'
YELLOW = '\033[1;33m'
BOLD = '\033[1m'
NC = '\033[0m'
def get_log_file() -> Path:
return PROJECT_ROOT / "bot.log"
def print_error(text: str):
print(f"{Colors.RED}✗ {text}{Colors.NC}")
def print_info(text: str):
print(f"{Colors.YELLOW}ℹ {text}{Colors.NC}")
def print_success(text: str):
print(f"{Colors.GREEN}✓ {text}{Colors.NC}")
def follow_logs():
"""Follow logs in real-time"""
log_file = get_log_file()
if not log_file.exists():
print_error(f"Log file not found: {log_file}")
return 1
print_info("Following bot logs (Ctrl+C to stop)...")
print("━" * 60)
try:
subprocess.run(["tail", "-f", str(log_file)])
except KeyboardInterrupt:
print("\n" + "━" * 60)
print_info("Stopped following logs")
return 0
def show_last_lines(n: int):
"""Show last N lines of log"""
log_file = get_log_file()
if not log_file.exists():
print_error(f"Log file not found: {log_file}")
return 1
print_info(f"Last {n} lines of bot logs:")
print("━" * 60)
try:
with open(log_file, 'r') as f:
lines = f.readlines()
for line in lines[-n:]:
print(line.rstrip())
except Exception as e:
print_error(f"Failed to read log: {e}")
return 1
return 0
def show_errors():
"""Show only error lines"""
log_file = get_log_file()
if not log_file.exists():
print_error(f"Log file not found: {log_file}")
return 1
print_info("Errors in bot logs:")
print("━" * 60)
try:
error_keywords = ['error', 'exception', 'failed', 'traceback']
errors = []
with open(log_file, 'r') as f:
for line in f:
if any(keyword in line.lower() for keyword in error_keywords):
errors.append(line.rstrip())
if errors:
# Show last 20 errors
for error in errors[-20:]:
print(error)
else:
print_success("No errors found in logs")
except Exception as e:
print_error(f"Failed to read log: {e}")
return 1
return 0
def clear_logs():
"""Clear the log file"""
log_file = get_log_file()
if not log_file.exists():
print_error(f"Log file not found: {log_file}")
return 1
response = input("⚠️ Are you sure you want to clear the log file? (y/n): ").strip().lower()
if response != 'y':
print("Aborted")
return 0
try:
log_file.write_text("")
print_success("Log file cleared")
return 0
except Exception as e:
print_error(f"Failed to clear log: {e}")
return 1
def main():
parser = argparse.ArgumentParser(
description="IRIS Bot Log Viewer - View and manage bot logs",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
python scripts/logs_bot.py # Follow logs in real-time
python scripts/logs_bot.py last -n 100 # Show last 100 lines
python scripts/logs_bot.py errors # Show only errors
python scripts/logs_bot.py clear # Clear log file
"""
)
parser.add_argument(
'mode',
nargs='?',
choices=['follow', 'last', 'errors', 'clear'],
default='follow',
help='Mode to run (default: follow)'
)
parser.add_argument(
'-n', '--lines',
type=int,
default=50,
help='Number of lines to show (for "last" mode, default: 50)'
)
args = parser.parse_args()
try:
if args.mode == 'follow':
return follow_logs()
elif args.mode == 'last':
return show_last_lines(args.lines)
elif args.mode == 'errors':
return show_errors()
elif args.mode == 'clear':
return clear_logs()
else:
parser.print_help()
return 1
except KeyboardInterrupt:
print("\n\n❌ Interrupted by user")
return 1
except Exception as e:
print_error(f"Unexpected error: {e}")
import traceback
traceback.print_exc()
return 1
if __name__ == "__main__":
sys.exit(main())