finish logging

This commit is contained in:
Désiré Werner Menrath 2025-05-23 12:36:28 +02:00
parent 5ac37ad9ad
commit 79f6fc0265
6 changed files with 83 additions and 103 deletions

View File

@ -15,7 +15,7 @@ import zipfile
from datetime import datetime from datetime import datetime
from pathlib import Path from pathlib import Path
from tkinter import ttk, Toplevel from tkinter import ttk, Toplevel
from wp_app_config import AppConfig, Msg from wp_app_config import AppConfig, Msg, logging
import requests import requests
# Translate # Translate
@ -46,12 +46,14 @@ class CryptoUtil:
# Output from Openssl Error # Output from Openssl Error
if process.stderr: if process.stderr:
print(process.stderr) logging.error(process.stderr, exc_info=True)
if process.returncode == 0: if process.returncode == 0:
print("Files successfully decrypted...") logging.info("Files successfully decrypted...", exc_info=True)
else: else:
print(f"Error process decrypt: Code {process.returncode}") logging.error(
f"Error process decrypt: Code {process.returncode}", exc_info=True
)
@staticmethod @staticmethod
def encrypt(user) -> None: def encrypt(user) -> None:
@ -67,12 +69,14 @@ class CryptoUtil:
# Output from Openssl Error # Output from Openssl Error
if process.stderr: if process.stderr:
print(process.stderr) logging.error(process.stderr, exc_info=True)
if process.returncode == 0: if process.returncode == 0:
print("Files successfully encrypted...") logging.info("Files successfully encrypted...", exc_info=True)
else: else:
print(f"Error process encrypt: Code {process.returncode}") logging.error(
f"Error process encrypt: Code {process.returncode}", exc_info=True
)
@staticmethod @staticmethod
def find_key(key: str = "") -> bool: def find_key(key: str = "") -> bool:
@ -90,8 +94,9 @@ class CryptoUtil:
return True return True
elif "False" in process.stdout: elif "False" in process.stdout:
return False return False
print( logging.error(
f"Unexpected output from the external script:\nSTDOUT: {process.stdout}\nSTDERR: {process.stderr}" f"Unexpected output from the external script:\nSTDOUT: {process.stdout}\nSTDERR: {process.stderr}",
exc_info=True,
) )
return False return False
@ -310,13 +315,13 @@ class LxTools:
msg.title(w_title) msg.title(w_title)
msg.configure(pady=15, padx=15) msg.configure(pady=15, padx=15)
# Lade das erste Bild für das Fenster # load first image for window
try: try:
msg.img = tk.PhotoImage(file=image_path) msg.img = tk.PhotoImage(file=image_path)
msg.i_window = tk.Label(msg, image=msg.img) msg.i_window = tk.Label(msg, image=msg.img)
except Exception as e: except Exception as e:
print(f"Fehler beim Laden des Fensterbildes: {e}") logging.error(f"Error on load Window Image: {e}", exc_info=True)
msg.i_window = tk.Label(msg, text="Bild nicht gefunden") msg.i_window = tk.Label(msg, text="Image not found")
label: tk.Label = tk.Label(msg, text=w_txt) label: tk.Label = tk.Label(msg, text=w_txt)
label.grid(column=1, row=0) label.grid(column=1, row=0)
@ -340,12 +345,11 @@ class LxTools:
) )
button.grid(column=0, columnspan=2, row=1) button.grid(column=0, columnspan=2, row=1)
# Lade das Icon für das Fenster
try: try:
icon = tk.PhotoImage(file=image_path2) icon = tk.PhotoImage(file=image_path2)
msg.iconphoto(True, icon) msg.iconphoto(True, icon)
except Exception as e: except Exception as e:
print(f"Fehler beim Laden des Fenstericons: {e}") logging.error(f"Error loading the window icon: {e}", exc_info=True)
msg.columnconfigure(0, weight=1) msg.columnconfigure(0, weight=1)
msg.rowconfigure(0, weight=1) msg.rowconfigure(0, weight=1)
@ -385,16 +389,17 @@ class LxTools:
# End program for certain signals, report to others only reception # End program for certain signals, report to others only reception
if signum in (signal.SIGINT, signal.SIGTERM): if signum in (signal.SIGINT, signal.SIGTERM):
exit_code: int = 1 exit_code: int = 1
print( logging.error(
f"\nSignal {signal_name} {signum} received. => Aborting with exit code {exit_code}." f"\nSignal {signal_name} {signum} received. => Aborting with exit code {exit_code}.",
exc_info=True,
) )
LxTools.clean_files(file_path, file) LxTools.clean_files(file_path, file)
print("Breakdown by user...") logging.info("Breakdown by user...")
sys.exit(exit_code) sys.exit(exit_code)
else: else:
print(f"Signal {signum} received and ignored.") logging.info(f"Signal {signum} received and ignored.")
LxTools.clean_files(file_path, file) LxTools.clean_files(file_path, file)
print("Process unexpectedly ended...") logging.error("Process unexpectedly ended...")
# Register signal handlers for various signals # Register signal handlers for various signals
signal.signal(signal.SIGINT, signal_handler) signal.signal(signal.SIGINT, signal_handler)
@ -464,7 +469,10 @@ class Tunnel:
elif directory is not None: elif directory is not None:
if not directory.exists() or not directory.is_dir(): if not directory.exists() or not directory.is_dir():
print("Temp directory does not exist or is not a directory.") logging.error(
"Temp directory does not exist or is not a directory.",
exc_info=True,
)
return None return None
# Get a list of all files in the directory # Get a list of all files in the directory

View File

@ -5,7 +5,7 @@ from pathlib import Path
import pwd import pwd
import shutil import shutil
from subprocess import CompletedProcess, run from subprocess import CompletedProcess, run
from wp_app_config import AppConfig from wp_app_config import AppConfig, logging
parser = argparse.ArgumentParser() parser = argparse.ArgumentParser()
parser.add_argument("--user", required=True, help="Username of the target file system") parser.add_argument("--user", required=True, help="Username of the target file system")
@ -17,7 +17,7 @@ try:
uid = user_info.pw_uid # User ID (e.g., 1000) uid = user_info.pw_uid # User ID (e.g., 1000)
gid = user_info.pw_gid # Group ID (e.g., 1000) gid = user_info.pw_gid # Group ID (e.g., 1000)
except KeyError: except KeyError:
print(f"User '{args.user}' not found.") logging.error(f"User '{args.user}' not found.", exc_info=True)
exit(1) exit(1)
keyfile: Path = Path(f"/home/{args.user}/.config/wire_py/pbwgk.pem") keyfile: Path = Path(f"/home/{args.user}/.config/wire_py/pbwgk.pem")
@ -40,11 +40,13 @@ if not keyfile.is_file():
text=True, text=True,
check=False, check=False,
) )
print(process.stdout)
if process.returncode == 0: if process.returncode == 0:
print("Public key generated successfully.") logging.info("Public key generated successfully.", exc_info=True)
else: else:
print(f"Error with the following code... {process.returncode}") logging.error(
f"Error with the following code... {process.returncode}", exc_info=True
)
shutil.chown(keyfile, uid, gid) shutil.chown(keyfile, uid, gid)
if AppConfig.PUBLICKEY.exists(): if AppConfig.PUBLICKEY.exists():
@ -72,16 +74,11 @@ if AppConfig.PUBLICKEY.exists():
check=False, check=False,
) )
shutil.chown(f"{AppConfig.TEMP_DIR}/{base_name}.conf", uid, gid) shutil.chown(f"{AppConfig.TEMP_DIR}/{base_name}.conf", uid, gid)
print(f"Processing of the file: {tunnel_path}") logging.info(f"Processing of the file: {tunnel_path}", exc_info=True)
if process.stdout:
print(process.stdout)
# Output from Openssl Error # Output from Openssl Error
if process.stderr: if process.stderr:
print("(Error):", process.stderr) logging.error(
f"{process.stderr} Error by [{tunnel_path}] Code: {process.returncode}",
if process.returncode == 0: exc_info=True,
print(f"File {base_name}.dat successfully decrypted.") )
else:
print(f"Error by {tunnel_path}: Code: {process.returncode}")

View File

@ -2,11 +2,12 @@
""" This Script encrypt Wireguardfiles for Wirepy users for more Security """ """ This Script encrypt Wireguardfiles for Wirepy users for more Security """
import argparse import argparse
import logging
from pathlib import Path from pathlib import Path
import pwd import pwd
import shutil import shutil
from subprocess import CompletedProcess, run from subprocess import CompletedProcess, run
from wp_app_config import AppConfig from wp_app_config import AppConfig, logging
parser = argparse.ArgumentParser() parser = argparse.ArgumentParser()
parser.add_argument("--user", required=True, help="Username of the target file system") parser.add_argument("--user", required=True, help="Username of the target file system")
@ -18,7 +19,7 @@ try:
uid = user_info.pw_uid # User ID (e.g., 1000) uid = user_info.pw_uid # User ID (e.g., 1000)
gid = user_info.pw_gid # Group ID (e.g., 1000) gid = user_info.pw_gid # Group ID (e.g., 1000)
except KeyError: except KeyError:
print(f"User '{args.user}' not found.") logging.error(f"User '{args.user}' not found.", exc_info=True)
exit(1) exit(1)
keyfile: Path = Path(f"/home/{args.user}/.config/wire_py/pbwgk.pem") keyfile: Path = Path(f"/home/{args.user}/.config/wire_py/pbwgk.pem")
@ -44,17 +45,12 @@ if not keyfile.is_file():
check=False, check=False,
) )
if process.stdout:
print(process.stdout)
# Output from Openssl Error # Output from Openssl Error
if process.stderr: if process.stderr:
print("(Error):", process.stderr) logging.error(f"{process.stderr} Code: {process.returncode}", exc_info=True)
if process.returncode == 0: if process.returncode == 0:
print("Public key generated successfully.") logging.info("Public key generated successfully.", exc_info=True)
else:
print(f"Error generate Publickey: Code: {process.returncode}")
shutil.chown(keyfile, uid, gid) shutil.chown(keyfile, uid, gid)
@ -82,13 +78,6 @@ if AppConfig.TEMP_DIR.exists() and any(AppConfig.TEMP_DIR.iterdir()):
check=False, check=False,
) )
print(f"Processing of the file: {config_file}")
# Output from Openssl Error # Output from Openssl Error
if process.stderr: if process.stderr:
print("(Error):", process.stderr) logging.error(process.stderr, exc_info=True)
if process.returncode == 0:
print(f"File {base_name}.dat successfully encrypted.")
else:
print(f"Error by {config_file}: Code: {process.returncode}")

View File

@ -4,7 +4,7 @@
""" """
from subprocess import CompletedProcess, run from subprocess import CompletedProcess, run
from wp_app_config import AppConfig from wp_app_config import AppConfig, logging
from common_tools import ConfigManager from common_tools import ConfigManager
ConfigManager.init(AppConfig.SETTINGS_FILE) ConfigManager.init(AppConfig.SETTINGS_FILE)
@ -18,7 +18,7 @@ if ConfigManager.get("autostart") != "off":
) )
# Output from start_wg error # Output from start_wg error
if process.stderr: if process.stderr:
print(process.stderr) # this is for the error, later on logfile logging.error(process.stderr, exc_info=True)
else: else:
pass pass

View File

@ -5,7 +5,6 @@ this script is a simple GUI for managing Wireguard Tunnels
import getpass import getpass
import shutil import shutil
import subprocess
import sys import sys
import tkinter as tk import tkinter as tk
import webbrowser import webbrowser
@ -22,7 +21,7 @@ from common_tools import (
Tooltip, Tooltip,
LxTools, LxTools,
) )
from wp_app_config import AppConfig, Msg from wp_app_config import AppConfig, Msg, logging
AppConfig.ensure_directories() AppConfig.ensure_directories()
AppConfig.create_default_settings() AppConfig.create_default_settings()
@ -522,7 +521,7 @@ class FrameWidgets(ttk.Frame):
# Now update the UI with the fresh result # Now update the UI with the fresh result
self.update_ui_for_update(res) self.update_ui_for_update(res)
except Exception as e: except Exception as e:
print(f"Error checking for updates: {e}") logging.error(f"Error checking for updates: {e}", exc_info=True)
# Fallback to a default message if there's an error # Fallback to a default message if there's an error
self.update_ui_for_update("No Internet Connection!") self.update_ui_for_update("No Internet Connection!")
@ -663,7 +662,6 @@ class FrameWidgets(ttk.Frame):
Msg.STR["invalid_base64"], Msg.STR["invalid_base64"],
) )
else: else:
print("Key is valid and does not exist import allowed!")
filepath = Path(filepath) filepath = Path(filepath)
# Shorten the tunnel name to the maximum allowed length if it exceeds 12 characters. # Shorten the tunnel name to the maximum allowed length if it exceeds 12 characters.
original_name = filepath.name original_name = filepath.name
@ -687,10 +685,8 @@ class FrameWidgets(ttk.Frame):
) )
if process.stderr: if process.stderr:
print(process.stderr) logging.error(f"{process.stderr}: Code {process.returncode}")
else:
print(f"Error process decrypt: Code {process.returncode}")
self.reset_fields() self.reset_fields()
process: CompletedProcess[str] = run( process: CompletedProcess[str] = run(
@ -709,12 +705,9 @@ class FrameWidgets(ttk.Frame):
) )
if process.stderr: if process.stderr:
print(process.stderr) logging.error(
f"{process.stderr} Code: {process.returncode}", exc_info=True
if process.returncode == 0: )
print(f"Tunnel >> {import_file.stem} << import successfull")
else:
print(f"Error process decrypt: Code {process.returncode}")
CryptoUtil.encrypt(getpass.getuser()) CryptoUtil.encrypt(getpass.getuser())
LxTools.clean_files(AppConfig.TEMP_DIR, file=None) LxTools.clean_files(AppConfig.TEMP_DIR, file=None)
@ -753,7 +746,7 @@ class FrameWidgets(ttk.Frame):
) )
if process.stderr: if process.stderr:
print(process.stderr) logging.error(process.stderr, exc_info=True)
if process.returncode == 0: if process.returncode == 0:
print(f">> {import_file.stem} << autostart is disabled by default") print(f">> {import_file.stem} << autostart is disabled by default")
@ -773,8 +766,6 @@ class FrameWidgets(ttk.Frame):
print("File import: abort by user...") print("File import: abort by user...")
except FileNotFoundError: except FileNotFoundError:
print("File import: abort by user...") print("File import: abort by user...")
except subprocess.CalledProcessError:
print("Tunnel exist!")
def delete(self) -> None: def delete(self) -> None:
""" """
@ -792,12 +783,9 @@ class FrameWidgets(ttk.Frame):
) )
if process.stderr: if process.stderr:
print(process.stderr) logging.error(
f"{process.stderr} Code: {process.returncode}", exc_info=True
if process.returncode == 0: )
print(f"Tunnel >> {select_tl} << successfully deleted...")
else:
print(f"Error process: Code {process.returncode}")
self.l_box.delete(self.select_tunnel[0]) self.l_box.delete(self.select_tunnel[0])
Path.unlink(f"{AppConfig.CONFIG_DIR}/{select_tl}.dat") Path.unlink(f"{AppConfig.CONFIG_DIR}/{select_tl}.dat")
@ -871,9 +859,6 @@ class FrameWidgets(ttk.Frame):
""" """
if ConfigManager.get("autostart") != "off": if ConfigManager.get("autostart") != "off":
print(
f"{ConfigManager.get("autostart")} starts automatically when the system starts."
)
self.selected_option.set(1) self.selected_option.set(1)
self.autoconnect_var.set("") self.autoconnect_var.set("")
self.auto_con = ConfigManager.get("autostart") self.auto_con = ConfigManager.get("autostart")
@ -992,10 +977,9 @@ class FrameWidgets(ttk.Frame):
check=False, check=False,
) )
if process.stderr: if process.stderr:
print(process.stderr) logging.error(
f"{process.stderr} Code: {process.returncode}", exc_info=True
if process.returncode != 0: )
print(f"Error process: Code {process.returncode}")
source = Path(f"{AppConfig.CONFIG_DIR}/{select_tl}.dat") source = Path(f"{AppConfig.CONFIG_DIR}/{select_tl}.dat")
destination = AppConfig.CONFIG_DIR / f"{self.lb_rename.get()}.dat" destination = AppConfig.CONFIG_DIR / f"{self.lb_rename.get()}.dat"
@ -1019,11 +1003,8 @@ class FrameWidgets(ttk.Frame):
Msg.STR["sel_list"], Msg.STR["sel_list"],
) )
except subprocess.CalledProcessError:
pass
except EOFError as e: except EOFError as e:
print(e) logging.error(e, exc_info=True)
def handle_tunnel_data(self, active=None, data=None) -> None: def handle_tunnel_data(self, active=None, data=None) -> None:
"""Processes tunnel data from an active connection and updates """Processes tunnel data from an active connection and updates
@ -1127,10 +1108,9 @@ class FrameWidgets(ttk.Frame):
) )
if process.stderr: if process.stderr:
print(process.stderr) logging.error(
f"{process.stderr} Code: {process.returncode}", exc_info=True
if process.returncode != 0: )
print(f"Error process: Code {process.returncode}")
self.update_connection_display() self.update_connection_display()
self.reset_fields() self.reset_fields()
@ -1147,12 +1127,9 @@ class FrameWidgets(ttk.Frame):
) )
if process.stderr: if process.stderr:
print(process.stderr) logging.error(
f"{process.stderr} Code: {process.returncode}", exc_info=True
if process.returncode == 0: )
print(f"Tunnel >> {target_tunnel} << started")
else:
print(f"Error process: Code {process.returncode}")
self.update_connection_display() self.update_connection_display()
self.handle_tunnel_data(self.a, self.tl) self.handle_tunnel_data(self.a, self.tl)

View File

@ -1,6 +1,6 @@
#!/usr/bin/python3 #!/usr/bin/python3
"""App configuration for Wire-Py""" """App configuration for Wire-Py"""
import logging
import gettext import gettext
import locale import locale
from pathlib import Path from pathlib import Path
@ -28,6 +28,17 @@ class AppConfig:
consistently and perform system-level setup tasks. consistently and perform system-level setup tasks.
""" """
# Logging
LOG_DIR = Path.home() / ".local/share/wirepy"
Path(LOG_DIR).mkdir(parents=True, exist_ok=True)
LOG_FILE_PATH = LOG_DIR / "wirepy.log"
logging.basicConfig(
filename=f"{LOG_FILE_PATH}",
level=logging.ERROR,
format="%(asctime)s - %(levelname)s - %(message)s",
)
# Localization # Localization
APP_NAME: str = "wirepy" APP_NAME: str = "wirepy"
LOCALE_DIR: Path = Path("/usr/share/locale/") LOCALE_DIR: Path = Path("/usr/share/locale/")
@ -145,11 +156,9 @@ class AppConfig:
text=True, text=True,
check=False, check=False,
) )
print(process.stdout)
if process.returncode == 0: if process.stderr:
print(process.stdout) logging.error(f"{process.stderr} Code: {process.returncode}", exc_info=True)
else:
print(f"Error with the following code... {process.returncode}")
# here is inizialize the class for translate strrings # here is inizialize the class for translate strrings