replace prints with logging

fixes #144: printing non-ascii characters in a macOS application
opened directly from finder would sometimes lead to an error
message in /var/log/system.log similar to this:

  Failed to execute script 'dangerzone' due to unhandled exception:
  'ascii' codec can't encode character '\u201c' in position 1:
  ordinal not in range(128)
This commit is contained in:
deeplow 2022-08-09 15:42:19 +01:00
parent c2a140807f
commit 67d91be81a
No known key found for this signature in database
GPG key ID: 577982871529A52A
7 changed files with 63 additions and 31 deletions

View file

@ -2,6 +2,7 @@ import os
import sys import sys
import json import json
import click import click
import logging
from colorama import Fore, Style from colorama import Fore, Style
from .global_common import GlobalCommon from .global_common import GlobalCommon
@ -19,6 +20,7 @@ def print_header(s):
@click.option("--ocr-lang", help="Language to OCR, defaults to none") @click.option("--ocr-lang", help="Language to OCR, defaults to none")
@click.argument("filename", required=True) @click.argument("filename", required=True)
def cli_main(output_filename, ocr_lang, filename): def cli_main(output_filename, ocr_lang, filename):
setup_logging()
global_common = GlobalCommon() global_common = GlobalCommon()
common = Common() common = Common()
@ -113,3 +115,11 @@ def cli_main(output_filename, ocr_lang, filename):
else: else:
print_header("Failed to convert document") print_header("Failed to convert document")
sys.exit(-1) sys.exit(-1)
def setup_logging() -> None:
if getattr(sys, "dangerzone_dev", True):
fmt = "%(message)s"
logging.basicConfig(level=logging.DEBUG, format=fmt)
else:
logging.basicConfig(level=logging.ERROR, format=fmt)

View file

@ -2,6 +2,7 @@ import platform
import subprocess import subprocess
import pipes import pipes
import shutil import shutil
import logging
import os import os
import tempfile import tempfile
import appdirs import appdirs
@ -20,6 +21,7 @@ if platform.system() == "Windows":
else: else:
startupinfo = None startupinfo = None
log = logging.getLogger(__name__)
# Name of the dangerzone container # Name of the dangerzone container
container_name = "dangerzone.rocks/dangerzone" container_name = "dangerzone.rocks/dangerzone"
@ -27,7 +29,7 @@ container_name = "dangerzone.rocks/dangerzone"
def exec(args, stdout_callback=None): def exec(args, stdout_callback=None):
args_str = " ".join(pipes.quote(s) for s in args) args_str = " ".join(pipes.quote(s) for s in args)
print("> " + args_str) log.info("> " + args_str)
with subprocess.Popen( with subprocess.Popen(
args, args,
@ -95,7 +97,7 @@ def convert(input_filename, output_filename, ocr_lang, stdout_callback):
) )
ret = exec_container(args, stdout_callback) ret = exec_container(args, stdout_callback)
if ret != 0: if ret != 0:
print("documents-to-pixels failed") log.error("documents-to-pixels failed")
else: else:
# TODO: validate convert to pixels output # TODO: validate convert to pixels output
@ -120,7 +122,7 @@ def convert(input_filename, output_filename, ocr_lang, stdout_callback):
) )
ret = exec_container(args, stdout_callback) ret = exec_container(args, stdout_callback)
if ret != 0: if ret != 0:
print("pixels-to-pdf failed") log.error("pixels-to-pdf failed")
else: else:
# Move the final file to the right place # Move the final file to the right place
if os.path.exists(output_filename): if os.path.exists(output_filename):

View file

@ -8,10 +8,13 @@ import json
import gzip import gzip
import colorama import colorama
from colorama import Fore, Back, Style from colorama import Fore, Back, Style
import logging
from .settings import Settings from .settings import Settings
from .container import convert from .container import convert
log = logging.getLogger(__name__)
class GlobalCommon(object): class GlobalCommon(object):
""" """
@ -224,8 +227,8 @@ class GlobalCommon(object):
""" """
print(Back.BLACK + Fore.YELLOW + Style.DIM + "╭──────────────────────────╮") log.info(Back.BLACK + Fore.YELLOW + Style.DIM + "╭──────────────────────────╮")
print( log.info(
Back.BLACK Back.BLACK
+ Fore.YELLOW + Fore.YELLOW
+ Style.DIM + Style.DIM
@ -237,7 +240,7 @@ class GlobalCommon(object):
+ Style.DIM + Style.DIM
+ "" + ""
) )
print( log.info(
Back.BLACK Back.BLACK
+ Fore.YELLOW + Fore.YELLOW
+ Style.DIM + Style.DIM
@ -249,7 +252,7 @@ class GlobalCommon(object):
+ Style.DIM + Style.DIM
+ "" + ""
) )
print( log.info(
Back.BLACK Back.BLACK
+ Fore.YELLOW + Fore.YELLOW
+ Style.DIM + Style.DIM
@ -261,7 +264,7 @@ class GlobalCommon(object):
+ Style.DIM + Style.DIM
+ "" + ""
) )
print( log.info(
Back.BLACK Back.BLACK
+ Fore.YELLOW + Fore.YELLOW
+ Style.DIM + Style.DIM
@ -273,7 +276,7 @@ class GlobalCommon(object):
+ Style.DIM + Style.DIM
+ "" + ""
) )
print( log.info(
Back.BLACK Back.BLACK
+ Fore.YELLOW + Fore.YELLOW
+ Style.DIM + Style.DIM
@ -285,7 +288,7 @@ class GlobalCommon(object):
+ Style.DIM + Style.DIM
+ "" + ""
) )
print( log.info(
Back.BLACK Back.BLACK
+ Fore.YELLOW + Fore.YELLOW
+ Style.DIM + Style.DIM
@ -297,7 +300,7 @@ class GlobalCommon(object):
+ Style.DIM + Style.DIM
+ "" + ""
) )
print( log.info(
Back.BLACK Back.BLACK
+ Fore.YELLOW + Fore.YELLOW
+ Style.DIM + Style.DIM
@ -309,7 +312,7 @@ class GlobalCommon(object):
+ Style.DIM + Style.DIM
+ "" + ""
) )
print( log.info(
Back.BLACK Back.BLACK
+ Fore.YELLOW + Fore.YELLOW
+ Style.DIM + Style.DIM
@ -321,7 +324,7 @@ class GlobalCommon(object):
+ Style.DIM + Style.DIM
+ "" + ""
) )
print( log.info(
Back.BLACK Back.BLACK
+ Fore.YELLOW + Fore.YELLOW
+ Style.DIM + Style.DIM
@ -333,7 +336,7 @@ class GlobalCommon(object):
+ Style.DIM + Style.DIM
+ "" + ""
) )
print( log.info(
Back.BLACK Back.BLACK
+ Fore.YELLOW + Fore.YELLOW
+ Style.DIM + Style.DIM
@ -345,12 +348,12 @@ class GlobalCommon(object):
+ Style.DIM + Style.DIM
+ "" + ""
) )
print(Back.BLACK + Fore.YELLOW + Style.DIM + "│ │") log.info(Back.BLACK + Fore.YELLOW + Style.DIM + "│ │")
left_spaces = (15 - len(self.version) - 1) // 2 left_spaces = (15 - len(self.version) - 1) // 2
right_spaces = left_spaces right_spaces = left_spaces
if left_spaces + len(self.version) + 1 + right_spaces < 15: if left_spaces + len(self.version) + 1 + right_spaces < 15:
right_spaces += 1 right_spaces += 1
print( log.info(
Back.BLACK Back.BLACK
+ Fore.YELLOW + Fore.YELLOW
+ Style.DIM + Style.DIM
@ -364,7 +367,7 @@ class GlobalCommon(object):
+ Style.DIM + Style.DIM
+ "" + ""
) )
print( log.info(
Back.BLACK Back.BLACK
+ Fore.YELLOW + Fore.YELLOW
+ Style.DIM + Style.DIM
@ -377,7 +380,7 @@ class GlobalCommon(object):
+ Style.DIM + Style.DIM
+ "" + ""
) )
print(Back.BLACK + Fore.YELLOW + Style.DIM + "╰──────────────────────────╯") log.info(Back.BLACK + Fore.YELLOW + Style.DIM + "╰──────────────────────────╯")
def get_container_runtime(self): def get_container_runtime(self):
if platform.system() == "Linux": if platform.system() == "Linux":
@ -423,7 +426,7 @@ class GlobalCommon(object):
return return
# Load the container into podman # Load the container into podman
print("Installing Dangerzone container image...") log.info("Installing Dangerzone container image...")
p = subprocess.Popen( p = subprocess.Popen(
[self.get_container_runtime(), "load"], [self.get_container_runtime(), "load"],
@ -443,10 +446,10 @@ class GlobalCommon(object):
p.communicate() p.communicate()
if not self.is_container_installed(): if not self.is_container_installed():
print("Failed to install the container image") log.error("Failed to install the container image")
return False return False
print("Container image installed") log.info("Container image installed")
return True return True
def is_container_installed(self): def is_container_installed(self):
@ -478,7 +481,7 @@ class GlobalCommon(object):
elif found_image_id == "": elif found_image_id == "":
pass pass
else: else:
print("Deleting old dangerzone container image") log.info("Deleting old dangerzone container image")
try: try:
subprocess.check_output( subprocess.check_output(
@ -486,6 +489,6 @@ class GlobalCommon(object):
startupinfo=self.get_subprocess_startupinfo(), startupinfo=self.get_subprocess_startupinfo(),
) )
except: except:
print("Couldn't delete old container image, so leaving it there") log.warning("Couldn't delete old container image, so leaving it there")
return installed return installed

View file

@ -4,6 +4,7 @@ import signal
import platform import platform
import click import click
import uuid import uuid
import logging
from PySide2 import QtCore, QtWidgets from PySide2 import QtCore, QtWidgets
from .common import GuiCommon from .common import GuiCommon
@ -45,6 +46,8 @@ class ApplicationWrapper(QtCore.QObject):
@click.command() @click.command()
@click.argument("filename", required=False) @click.argument("filename", required=False)
def gui_main(filename): def gui_main(filename):
setup_logging()
if platform.system() == "Darwin": if platform.system() == "Darwin":
# Required for macOS Big Sur: https://stackoverflow.com/a/64878899 # Required for macOS Big Sur: https://stackoverflow.com/a/64878899
os.environ["QT_MAC_WANTS_LAYER"] = "1" os.environ["QT_MAC_WANTS_LAYER"] = "1"
@ -146,3 +149,7 @@ def gui_main(filename):
ret = app.exec_() ret = app.exec_()
sys.exit(ret) sys.exit(ret)
def setup_logging() -> None:
logging.basicConfig(level=logging.DEBUG, format="[%(levelname)s] %(message)s")

View file

@ -5,6 +5,7 @@ import shlex
import pipes import pipes
from PySide2 import QtCore, QtGui, QtWidgets from PySide2 import QtCore, QtGui, QtWidgets
from colorama import Fore from colorama import Fore
import logging
if platform.system() == "Darwin": if platform.system() == "Darwin":
import plistlib import plistlib
@ -16,6 +17,8 @@ elif platform.system() == "Linux":
from ..settings import Settings from ..settings import Settings
log = logging.getLogger(__name__)
class GuiCommon(object): class GuiCommon(object):
""" """
@ -52,7 +55,7 @@ class GuiCommon(object):
# Run # Run
args_str = " ".join(pipes.quote(s) for s in args) args_str = " ".join(pipes.quote(s) for s in args)
print(Fore.YELLOW + "> " + Fore.CYAN + args_str) log.info(Fore.YELLOW + "> " + Fore.CYAN + args_str)
subprocess.run(args) subprocess.run(args)
elif platform.system() == "Linux": elif platform.system() == "Linux":
@ -72,7 +75,7 @@ class GuiCommon(object):
# Open as a background process # Open as a background process
args_str = " ".join(pipes.quote(s) for s in args) args_str = " ".join(pipes.quote(s) for s in args)
print(Fore.YELLOW + "> " + Fore.CYAN + args_str) log.info(Fore.YELLOW + "> " + Fore.CYAN + args_str)
subprocess.Popen(args) subprocess.Popen(args)
def _find_pdf_viewers(self): def _find_pdf_viewers(self):

View file

@ -4,12 +4,15 @@ import tempfile
import subprocess import subprocess
import json import json
import shutil import shutil
import logging
from PySide2 import QtCore, QtGui, QtWidgets from PySide2 import QtCore, QtGui, QtWidgets
from colorama import Style, Fore from colorama import Style, Fore
from ..common import Common from ..common import Common
from ..container import convert from ..container import convert
log = logging.getLogger(__name__)
class MainWindow(QtWidgets.QMainWindow): class MainWindow(QtWidgets.QMainWindow):
delete_window = QtCore.Signal(str) delete_window = QtCore.Signal(str)
@ -154,7 +157,7 @@ class WaitingWidget(QtWidgets.QWidget):
container_runtime = shutil.which("docker") container_runtime = shutil.which("docker")
if container_runtime is None: if container_runtime is None:
print("Docker is not installed") log.error("Docker is not installed")
state = "not_installed" state = "not_installed"
else: else:
@ -167,7 +170,7 @@ class WaitingWidget(QtWidgets.QWidget):
) as p: ) as p:
p.communicate() p.communicate()
if p.returncode != 0: if p.returncode != 0:
print("Docker is not running") log.error("Docker is not running")
state = "not_running" state = "not_running"
else: else:
# Always try installing the container # Always try installing the container
@ -515,7 +518,7 @@ class ConvertThread(QtCore.QThread):
try: try:
status = json.loads(line) status = json.loads(line)
except: except:
print(f"Invalid JSON returned from container: {line}") log.error(f"Invalid JSON returned from container: {line}")
self.error = True self.error = True
self.update.emit( self.update.emit(
True, f"Invalid JSON returned from container:\n\n{line}", 0 True, f"Invalid JSON returned from container:\n\n{line}", 0
@ -526,9 +529,10 @@ class ConvertThread(QtCore.QThread):
if status["error"]: if status["error"]:
self.error = True self.error = True
s += Style.RESET_ALL + Fore.RED + status["text"] s += Style.RESET_ALL + Fore.RED + status["text"]
log.error(s)
else: else:
s += Style.RESET_ALL + status["text"] s += Style.RESET_ALL + status["text"]
print(s) log.info(s)
self.update.emit(status["error"], status["text"], status["percentage"]) self.update.emit(status["error"], status["text"], status["percentage"])

View file

@ -1,6 +1,9 @@
import os import os
import json import json
import appdirs import appdirs
import logging
log = logging.getLogger(__name__)
class Settings: class Settings:
@ -36,12 +39,12 @@ class Settings:
self.settings[key] = self.default_settings[key] self.settings[key] = self.default_settings[key]
except: except:
print("Error loading settings, falling back to default") log.error("Error loading settings, falling back to default")
self.settings = self.default_settings self.settings = self.default_settings
else: else:
# Save with default settings # Save with default settings
print("Settings file doesn't exist, starting with default") log.info("Settings file doesn't exist, starting with default")
self.settings = self.default_settings self.settings = self.default_settings
self.save() self.save()