Add logging functionality: log print actions to logs folder with 5-day auto-cleanup
This commit is contained in:
@@ -20,6 +20,8 @@ import os
|
|||||||
import threading
|
import threading
|
||||||
import platform
|
import platform
|
||||||
import time
|
import time
|
||||||
|
import datetime
|
||||||
|
import glob
|
||||||
from print_label import print_label_standalone, get_available_printers
|
from print_label import print_label_standalone, get_available_printers
|
||||||
from kivy.clock import Clock
|
from kivy.clock import Clock
|
||||||
|
|
||||||
@@ -39,6 +41,8 @@ class LabelPrinterApp(App):
|
|||||||
self.available_printers = self.get_available_printers()
|
self.available_printers = self.get_available_printers()
|
||||||
# Clean old PDF backup files on startup
|
# Clean old PDF backup files on startup
|
||||||
self.cleanup_old_pdfs()
|
self.cleanup_old_pdfs()
|
||||||
|
# Clean old log files on startup
|
||||||
|
self.cleanup_old_logs()
|
||||||
|
|
||||||
def get_available_printers(self):
|
def get_available_printers(self):
|
||||||
"""Get list of available printers (cross-platform)"""
|
"""Get list of available printers (cross-platform)"""
|
||||||
@@ -81,6 +85,87 @@ class LabelPrinterApp(App):
|
|||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"Error during PDF cleanup: {e}")
|
print(f"Error during PDF cleanup: {e}")
|
||||||
|
|
||||||
|
def cleanup_old_logs(self, days=5):
|
||||||
|
"""
|
||||||
|
Delete log files older than specified days from logs folder.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
days (int): Delete files older than this many days (default: 5)
|
||||||
|
"""
|
||||||
|
logs_dir = 'logs'
|
||||||
|
|
||||||
|
# Create folder if it doesn't exist
|
||||||
|
if not os.path.exists(logs_dir):
|
||||||
|
os.makedirs(logs_dir, exist_ok=True)
|
||||||
|
return
|
||||||
|
|
||||||
|
try:
|
||||||
|
current_time = time.time()
|
||||||
|
cutoff_time = current_time - (days * 24 * 3600) # Convert days to seconds
|
||||||
|
|
||||||
|
for filename in os.listdir(logs_dir):
|
||||||
|
file_path = os.path.join(logs_dir, filename)
|
||||||
|
|
||||||
|
# Only process log files
|
||||||
|
if not filename.endswith('.log'):
|
||||||
|
continue
|
||||||
|
|
||||||
|
# Check if file is older than cutoff
|
||||||
|
if os.path.isfile(file_path):
|
||||||
|
file_mtime = os.path.getmtime(file_path)
|
||||||
|
if file_mtime < cutoff_time:
|
||||||
|
try:
|
||||||
|
os.remove(file_path)
|
||||||
|
print(f"Deleted old log: {filename}")
|
||||||
|
except Exception as e:
|
||||||
|
print(f"Failed to delete {filename}: {e}")
|
||||||
|
except Exception as e:
|
||||||
|
print(f"Error during log cleanup: {e}")
|
||||||
|
|
||||||
|
def log_print_action(self, sap_nr, quantity, cable_id, printer, pdf_filename, success):
|
||||||
|
"""
|
||||||
|
Log the print action to a log file.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
sap_nr (str): SAP article number
|
||||||
|
quantity (str): Quantity value
|
||||||
|
cable_id (str): Cable ID
|
||||||
|
printer (str): Printer name
|
||||||
|
pdf_filename (str): Path to the generated PDF file
|
||||||
|
success (bool): Whether the print was successful
|
||||||
|
"""
|
||||||
|
logs_dir = 'logs'
|
||||||
|
|
||||||
|
# Create logs folder if it doesn't exist
|
||||||
|
os.makedirs(logs_dir, exist_ok=True)
|
||||||
|
|
||||||
|
try:
|
||||||
|
# Create log filename with date
|
||||||
|
log_date = datetime.datetime.now().strftime("%Y%m%d")
|
||||||
|
log_filename = os.path.join(logs_dir, f"print_log_{log_date}.log")
|
||||||
|
|
||||||
|
# Create log entry
|
||||||
|
timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||||||
|
status = "SUCCESS" if success else "FAILED"
|
||||||
|
|
||||||
|
log_entry = (
|
||||||
|
f"[{timestamp}] {status}\n"
|
||||||
|
f" SAP-Nr: {sap_nr}\n"
|
||||||
|
f" Quantity: {quantity}\n"
|
||||||
|
f" Cable ID: {cable_id}\n"
|
||||||
|
f" Printer: {printer}\n"
|
||||||
|
f" PDF File: {pdf_filename}\n"
|
||||||
|
f" ---\n"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Append to log file
|
||||||
|
with open(log_filename, 'a', encoding='utf-8') as f:
|
||||||
|
f.write(log_entry)
|
||||||
|
|
||||||
|
print(f"Log entry saved to: {log_filename}")
|
||||||
|
except Exception as e:
|
||||||
|
print(f"Error saving log entry: {e}")
|
||||||
|
|
||||||
def build(self):
|
def build(self):
|
||||||
"""Build the simplified single-column UI"""
|
"""Build the simplified single-column UI"""
|
||||||
self.title = "Label Printing"
|
self.title = "Label Printing"
|
||||||
@@ -246,18 +331,37 @@ class LabelPrinterApp(App):
|
|||||||
|
|
||||||
# Print in background thread (using PDF by default)
|
# Print in background thread (using PDF by default)
|
||||||
def print_thread():
|
def print_thread():
|
||||||
|
pdf_filename = None
|
||||||
|
success = False
|
||||||
try:
|
try:
|
||||||
success = print_label_standalone(label_text, printer, preview=0, use_pdf=True)
|
success = print_label_standalone(label_text, printer, preview=0, use_pdf=True)
|
||||||
|
|
||||||
|
# Get the PDF filename that was created
|
||||||
|
# Files are saved to pdf_backup/ with timestamp
|
||||||
|
pdf_files = glob.glob('pdf_backup/final_label_*.pdf')
|
||||||
|
if pdf_files:
|
||||||
|
# Get the most recently created PDF file
|
||||||
|
pdf_filename = max(pdf_files, key=os.path.getctime)
|
||||||
|
|
||||||
if success:
|
if success:
|
||||||
|
# Log the successful print action
|
||||||
|
self.log_print_action(sap_nr, quantity, cable_id, printer, pdf_filename or "unknown", True)
|
||||||
|
|
||||||
# Use Clock.schedule_once to update UI from main thread
|
# Use Clock.schedule_once to update UI from main thread
|
||||||
Clock.schedule_once(lambda dt: popup.dismiss(), 0)
|
Clock.schedule_once(lambda dt: popup.dismiss(), 0)
|
||||||
Clock.schedule_once(lambda dt: self.show_popup("Success", "Label printed successfully!"), 0.1)
|
Clock.schedule_once(lambda dt: self.show_popup("Success", "Label printed successfully!"), 0.1)
|
||||||
# Clear inputs after successful print (but keep printer selection)
|
# Clear inputs after successful print (but keep printer selection)
|
||||||
Clock.schedule_once(lambda dt: self.clear_inputs(), 0.2)
|
Clock.schedule_once(lambda dt: self.clear_inputs(), 0.2)
|
||||||
else:
|
else:
|
||||||
|
# Log the failed print action
|
||||||
|
self.log_print_action(sap_nr, quantity, cable_id, printer, pdf_filename or "unknown", False)
|
||||||
|
|
||||||
Clock.schedule_once(lambda dt: popup.dismiss(), 0)
|
Clock.schedule_once(lambda dt: popup.dismiss(), 0)
|
||||||
Clock.schedule_once(lambda dt: self.show_popup("Error", "Failed to print label"), 0.1)
|
Clock.schedule_once(lambda dt: self.show_popup("Error", "Failed to print label"), 0.1)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
|
# Log the error
|
||||||
|
self.log_print_action(sap_nr, quantity, cable_id, printer, pdf_filename or "unknown", False)
|
||||||
|
|
||||||
Clock.schedule_once(lambda dt: popup.dismiss(), 0)
|
Clock.schedule_once(lambda dt: popup.dismiss(), 0)
|
||||||
Clock.schedule_once(lambda dt: self.show_popup("Error", f"Print error: {str(e)}"), 0.1)
|
Clock.schedule_once(lambda dt: self.show_popup("Error", f"Print error: {str(e)}"), 0.1)
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user