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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,6 +1,6 @@
#!/usr/bin/python3
"""App configuration for Wire-Py"""
import logging
import gettext
import locale
from pathlib import Path
@ -28,6 +28,17 @@ class AppConfig:
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
APP_NAME: str = "wirepy"
LOCALE_DIR: Path = Path("/usr/share/locale/")
@ -145,11 +156,9 @@ class AppConfig:
text=True,
check=False,
)
print(process.stdout)
if process.returncode == 0:
print(process.stdout)
else:
print(f"Error with the following code... {process.returncode}")
if process.stderr:
logging.error(f"{process.stderr} Code: {process.returncode}", exc_info=True)
# here is inizialize the class for translate strrings