Untitled
unknown
plain_text
6 months ago
3.0 kB
1
Indexable
Never
def purge_logs(): vm_list = get_VMList() for vm in vm_list: syslog_file = get_syslog_file_location(vm) retention_period = get_retention_period(vm) vm_details = get_vm_details() for vm in vm_details: vm_id = vm['vm_id'] vm_ip = vm['vm_ip'] bookmark_index = get_bookmark_index(vm_ip) print("VM:", vm_id) print("Syslog File Location:", syslog_file) print("Retention Period:", retention_period) print("Bookmark Index:", bookmark_index) print("Purging Logs...") try: #bookmark_line = linecache.getline(syslog_file, int(bookmark_index)) bookmark_line = linecache.getline(syslog_file, 7092032) print("Bookmark Line :", bookmark_line) except Exception as e: print("Exception while reading line from file:", e) return None if not bookmark_line: print("Bookmark line not found.") continue bookmark_timestamp = get_timestamp_from_line(bookmark_line) # Calculate the purging date (7 days before the bookmark timestamp) bookmark_date = datetime.datetime.strptime(bookmark_timestamp, "%Y-%m-%dT%H:%M:%S+00:00") purging_date = bookmark_date - datetime.timedelta(days=7) # Perform the log purging lines_to_keep = [] lines_purged = 0 # Counter for purged lines with open(syslog_file, "r") as file: for line in file: timestamp = get_timestamp_from_line(line) line_date = datetime.datetime.strptime(timestamp, "%Y-%m-%dT%H:%M:%S+00:00") if line_date > purging_date: lines_to_keep.append(line) else: lines_purged += 1 # Write the lines to keep back to the syslog file with open(syslog_file, "w") as file: file.writelines(lines_to_keep) print("Purging Completed") print(f"Lines Purged: {lines_purged}") print("Printing First Two Lines:") with open(syslog_file, "r") as file: print(file.readline()) print(file.readline()) print() purge_logs() When i Run the code- I get the output as - VM: 23 Syslog File Location: /var/log/syslog/LONSTBYRDEV02-10.72.209.183.log Retention Period: 7 Bookmark Index: 4212032 Purging Logs... Bookmark Line : Bookmark line not found. Ideally if we check /var/log/syslog/LONSTBYRDEV02-10.72.209.183.log this is the correct path of the log file and it contains a total of 5644752 lines. Also the particular line is present in the log file when we manually check using this- head -n 4212032 /var/log/syslog/LONSTBYRDEV02-10.72.209.183.log | tail -1 So if line content is present also , the filename is proper then why it is not able ti get the bookmark line from index using linecache.