Search code examples
pythonpyinstaller

How to log error information into file when using pyinstaller with --no-console?


As you may know, if using pyinstaller to package python files, there is an option called no-console, so all error information and print result will not shown on screen. My question is if there is any other solution that can let me write those error information and even print result into a log file? I know we can use try-except in python to catch error, but what if an error I did not catch? I hope there is a way so we can log all stdout and stderr into a file, so we can check it later. Thanks!


Solution

  • This is a later answer but I solved it with sys.excepthook

    I set up a logger and an exception hook for all uncaught exceptions like so:

    def exception_hook(exc_type, exc_value, exc_traceback):
       logging.error(
           "Uncaught exception",
           exc_info=(exc_type, exc_value, exc_traceback)
       )
       sys.exit()
    
    def set_up_logger():
        date_time_obj = datetime.now()
        timestamp_str = date_time_obj.strftime("%d-%b-%Y_%H_%M_%S")
        filename = './Log/crash-{}.log'.format(timestamp_str)
        logging.basicConfig(filename=filename)
        sys.excepthook = exception_hook
    

    Then just call your set_up_logger function in your main. This works for windowed pyinstaller applications.