Python实现RAM中CPU日志文件固定条目轮转求助
Hey there! Let's work through your log rotation problem for your CPU monitoring script. I see you've already got the basic tracking working, so let's focus on keeping those /tmp files from growing too big by limiting each to 60 entries.
First, let's fix the core rotation logic and clean up some inefficiencies in your original code. Here's a revised version that handles the 60-entry limit properly:
Improved CPU Monitoring Script with Log Rotation
#!/usr/bin/python import psutil import time def rotate_log(file_path, new_entry, max_entries=60): """Handle log rotation to keep only the last `max_entries` lines""" try: # Read existing lines from the file (if it exists) with open(file_path, 'r') as f: lines = f.readlines() # If we hit the entry limit, keep only the last 59 lines to make room for the new one if len(lines) >= max_entries: lines = lines[-(max_entries - 1):] # Write the truncated lines plus the new CPU usage entry with open(file_path, 'w') as f: f.writelines(lines) f.write(new_entry + '\n') except FileNotFoundError: # For the first run, just create the file and write the first entry with open(file_path, 'w') as f: f.write(new_entry + '\n') while True: # Get CPU usage once per loop (no need to call it three times!) cpu_usage = str(psutil.cpu_percent(interval=1)) # Update each log file with rotation logic rotate_log('/tmp/cpu_sec.txt', cpu_usage) rotate_log('/tmp/cpu_min.txt', cpu_usage) rotate_log('/tmp/cpu_hr.txt', cpu_usage) time.sleep(1)
Key Improvements:
- Reusable rotation function: The
rotate_logfunction handles all the heavy lifting for every file—reading existing entries, truncating when needed, and writing the new data. It also gracefully handles brand-new files. - Optimized CPU calls: Your original code called
psutil.cpu_percentthree times in a row, adding 3 seconds of delay per loop. Now we get the value once and reuse it for all three files. - Safe file handling: Using
withstatements ensures files are automatically closed after operations, preventing resource leaks.
Adjusting for Actual Time Intervals (Optional)
Wait a second—your original code writes to all three files every second, but I suspect you might have intended:
cpu_sec.txt: Update every 1 secondcpu_min.txt: Update every 60 secondscpu_hr.txt: Update every 3600 seconds
If that's the case, here's a version that fixes the intervals without unnecessary delays:
#!/usr/bin/python import psutil import time def rotate_log(file_path, new_entry, max_entries=60): try: with open(file_path, 'r') as f: lines = f.readlines() if len(lines) >= max_entries: lines = lines[-(max_entries - 1):] with open(file_path, 'w') as f: f.writelines(lines) f.write(new_entry + '\n') except FileNotFoundError: with open(file_path, 'w') as f: f.write(new_entry + '\n') # Track elapsed seconds for longer intervals sec_count = 0 while True: # Get CPU usage once per second cpu_usage = str(psutil.cpu_percent(interval=1)) # Update second log every loop rotate_log('/tmp/cpu_sec.txt', cpu_usage) sec_count += 1 # Update minute log every 60 seconds if sec_count % 60 == 0: rotate_log('/tmp/cpu_min.txt', cpu_usage) # Update hour log every 3600 seconds (1 hour) if sec_count % 3600 == 0: rotate_log('/tmp/cpu_hr.txt', cpu_usage) # Reset count to avoid integer bloat (optional) sec_count = 0
Quick Notes:
- RAM efficiency: Since we only read up to 60 lines per file at a time, the memory footprint stays tiny—perfect for your RAM-based
/tmpdirectory. - Simplicity: This approach is straightforward and works well for basic monitoring. If you need ultra-safe atomic writes (to avoid partial files if the script crashes), you could write to a temporary file first then replace the original, but that's probably overkill here.
内容的提问来源于stack exchange,提问作者Lokesh
相关产品推荐
相关产品推荐

