Skip to content

Commit 6404a1a

Browse files
committed
1.3.x loging in cmd mode added
1 parent 168cad6 commit 6404a1a

File tree

2 files changed

+53
-20
lines changed

2 files changed

+53
-20
lines changed

code/export-msaccess-sql.py

+36-20
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
import json
77
import argparse
88
from datetime import datetime
9+
from logger_cfg import logger, enable_file_logging
910

1011
parser = argparse.ArgumentParser(description="MS Access to SQL Export Tool")
1112

@@ -14,7 +15,7 @@ class GetWidgetsFrame(WidgetsRender, ttk.Frame):
1415
The main class of the program is responsible for constructing the form and interaction of elements
1516
"""
1617

17-
def __init__(self, render_params=None, *args, **options):
18+
def __init__(self, render_params=None, mode="", *args, **options):
1819
"""
1920
Initialization of the Frame, description of the main elements
2021
:param render_params: General parameters for the arrangement of elements can be set externally
@@ -36,6 +37,7 @@ def __init__(self, render_params=None, *args, **options):
3637
11: "Binary",
3738
12: "Text"
3839
}}
40+
self.mode = tk.StringVar(self, mode)
3941
self.db_path = tk.StringVar(self, "")
4042
self.sql_path = tk.StringVar(self, "")
4143
self.log_path = tk.StringVar(self, "")
@@ -221,15 +223,23 @@ def load_config(self, fpath='config.json', loadbyinit=False):
221223
self.sql_path.set(config["sql_path"])
222224
if "log_path" in config:
223225
self.log_path.set(config["log_path"])
226+
if self.mode.get() == "cmd":
227+
enable_file_logging(self.log_path.get())
228+
logger.info(f"Logging in file {self.log_path.get()} enabled")
224229
self.update_widgets()
225230
self.tree.df = self.tree.df.from_dict(config["tree"])
226231
self.tree.rebuild_tree()
227232
self.tree.all_checked_update()
233+
if self.mode.get() == "cmd":
234+
logger.info(f"Configuration`s uploaded: {fpath}")
228235
else:
229236
raise
230237
except:
231238
if loadbyinit:
232239
return
240+
if self.mode.get() == "cmd":
241+
logger.error(f"Configuration upload fail: {self.config_path.get()}")
242+
return
233243
fpath = filedialog.askopenfilename(filetypes=[("JSON files", "*.json")])
234244
if fpath:
235245
self.load_config(fpath)
@@ -289,7 +299,13 @@ def db_connect(self):
289299
if not db_path:
290300
return None
291301
engine = win32com.client.Dispatch("DAO.DBEngine.120")
292-
self.db = engine.OpenDatabase(db_path)
302+
try:
303+
self.db = engine.OpenDatabase(db_path)
304+
if self.mode.get() == "cmd":
305+
logger.info(f"DB connected: {db_path}")
306+
except Exception as e:
307+
if self.mode.get() == "cmd":
308+
logger.error(f"OpenDatabase({db_path}) failed: {e}")
293309

294310
def check_permissions(self):
295311
try:
@@ -349,13 +365,13 @@ def resolve_dependencies(self, export_list):
349365

350366
return list(export_set), list(added_tables)
351367

352-
def export_prepare(self, output_sql_path="", mode=""):
368+
def export_prepare(self, output_sql_path=""):
353369
df = self.tree.df
354370
export_list = df[df.iloc[:, 1] == "✔"]["table"].to_list()
355371
upload_list = df[df.iloc[:, 2] == "✔"]["table"].to_list()
356372
final_list, added_tables = self.resolve_dependencies(export_list)
357373

358-
if added_tables and mode != "cmd":
374+
if added_tables and self.mode.get() != "cmd":
359375
added_tables_str = "\n".join(added_tables)
360376
message = (
361377
"The following tables were added to ensure database integrity:\n\n"
@@ -364,18 +380,23 @@ def export_prepare(self, output_sql_path="", mode=""):
364380
)
365381
if not messagebox.askyesno("Integrity Check", message):
366382
return False
383+
elif self.mode.get() == "cmd":
384+
logger.info(f"Depended tables were added: {', '.join(added_tables)}")
385+
367386
if not output_sql_path:
368387
output_sql_path = self.get_output_sql_name()
369388

370389
return final_list, upload_list, output_sql_path
371390

372-
def export(self, mode=""):
373-
export_lists = self.export_prepare(self.sql_path.get(), mode=mode)
391+
def export(self):
392+
export_lists = self.export_prepare(self.sql_path.get())
374393
if not export_lists:
375394
return
376395

377396
with (open(export_lists[2], "w", encoding="utf-8") as sql_file):
378397
for tab_name in export_lists[0]:
398+
if self.mode.get() == "cmd":
399+
logger.info(f"Export table structure: {tab_name}.")
379400
table = self.db.TableDefs(tab_name)
380401
sql_file.write(f"-- Table: {table.Name}\n")
381402
sql_file.write(f"CREATE TABLE '{table.Name}' (\n")
@@ -419,6 +440,8 @@ def export(self, mode=""):
419440
sql_file.write("\n);\n\n")
420441

421442
if table.Name in export_lists[1]:
443+
if self.mode.get() == "cmd":
444+
logger.info(f"Export data from: {tab_name}.")
422445
ref_columns = [field.Name for field in table.Fields]
423446
sql_file.write(f"-- Filling data for {table.Name}\n")
424447
sql_file.write(f"INSERT INTO '{table.Name}' ({', '.join(ref_columns)}) VALUES\n")
@@ -440,31 +463,24 @@ def export(self, mode=""):
440463
recordset.MoveNext()
441464
recordset.Close()
442465
sql_file.write("\n);\n\n")
443-
if mode == "cmd":
444-
print(f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')} - SQL export completed!", f"File saved as {export_lists[2]}", sep="\n")
466+
if self.mode.get() == "cmd":
467+
logger.info(f"Table {tab_name} export complete.")
468+
if self.mode.get() == "cmd":
469+
logger.info(f"SQL export completed!")
445470
else:
446471
messagebox.showinfo("SQL export completed!", f"File saved as {export_lists[2]}")
447472

473+
448474
def main():
449475
parser.add_argument("-c","--config", type=str, help="Path to config file")
450476
args = parser.parse_args()
451-
452477
if args.config:
453-
log_list = []
454478
conf = args.config
455-
log_list.append(f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')} - Configuration`s accepted: {conf}")
456479
root.withdraw()
457-
app = GetWidgetsFrame(master=root)
458-
log_list.append(f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')} - App started: {app.master.title()}")
480+
app = GetWidgetsFrame(master=root, mode="cmd")
459481
app.load_config(conf)
460-
log_list.append(f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')} - Configuration`s uploaded:")
461-
log_list.append(f"\t db path: {app.db_path.get()}")
462-
log_list.append(f"\t sql path: {app.sql_path.get()}")
463-
log_list.append(f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')} - Export execution...")
464-
print("\n".join(log_list))
465-
app.export(mode="cmd")
482+
app.export()
466483
app.btn_exit()
467-
468484
else:
469485
app = GetWidgetsFrame(master=root, padding=(2, 2))
470486
app.mainloop()

code/logger_cfg.py

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import logging
2+
from logging.handlers import RotatingFileHandler
3+
4+
5+
logger = logging.getLogger("MSAccessExport")
6+
logger.setLevel(logging.INFO)
7+
formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")
8+
9+
console_handler = logging.StreamHandler()
10+
console_handler.setFormatter(formatter)
11+
logger.addHandler(console_handler)
12+
13+
def enable_file_logging(log_path="export.log"):
14+
file_handler = RotatingFileHandler(log_path, maxBytes=5 * 1024 * 1024, backupCount=3, encoding="utf-8")
15+
file_handler.setFormatter(formatter)
16+
logger.addHandler(file_handler)
17+

0 commit comments

Comments
 (0)