Fix logging in signal handler

Rebased version of #625. All credit goes to @christophermanning.