Change log format from text to CSV table format - easier to read and analyze

This commit is contained in:
Quality App Developer
2026-02-06 08:33:52 +02:00
parent 69e0f7f8b1
commit 37c7a5bd7a

View File

@@ -106,8 +106,8 @@ class LabelPrinterApp(App):
for filename in os.listdir(logs_dir):
file_path = os.path.join(logs_dir, filename)
# Only process log files
if not filename.endswith('.log'):
# Process both .log and .csv files
if not (filename.endswith('.log') or filename.endswith('.csv')):
continue
# Check if file is older than cutoff
@@ -124,7 +124,7 @@ class LabelPrinterApp(App):
def log_print_action(self, sap_nr, quantity, cable_id, printer, pdf_filename, success):
"""
Log the print action to a log file.
Log the print action to a CSV log file (table format).
Args:
sap_nr (str): SAP article number
@@ -142,25 +142,40 @@ class LabelPrinterApp(App):
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")
log_filename = os.path.join(logs_dir, f"print_log_{log_date}.csv")
# Create log entry
# Create log entry values
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"
# Escape CSV values (handle commas and quotes)
def escape_csv(value):
"""Escape CSV special characters"""
value = str(value)
if ',' in value or '"' in value or '\n' in value:
value = '"' + value.replace('"', '""') + '"'
return value
# Create CSV line
log_line = (
f"{timestamp},{status},"
f"{escape_csv(sap_nr)},"
f"{escape_csv(quantity)},"
f"{escape_csv(cable_id)},"
f"{escape_csv(printer)},"
f"{escape_csv(pdf_filename)}\n"
)
# Append to log file
# Check if file exists to add header on first entry
file_exists = os.path.isfile(log_filename)
# Write to log file
with open(log_filename, 'a', encoding='utf-8') as f:
f.write(log_entry)
# Add header if file is new
if not file_exists:
f.write("Timestamp,Status,SAP-Nr,Quantity,Cable ID,Printer,PDF File\n")
# Append log entry
f.write(log_line)
print(f"Log entry saved to: {log_filename}")
except Exception as e: