Use Thread to log message at exit

Clean up duplicate code
(cherry picked from commit 68ec8ac)