How to redirect tracebacks into a file on application crash?

Viewed 264

When app crashes we get stack track + maybe some more info. It usually gets printed to the console. I'd like to capture that action, and rather than letting print it to console I'd like to write it in to log file and disable the console print. I don't want to use try/else on each function/logic/

How can I do this?

2 Answers

The absolute simplest way – without doing any code changes – is to redirect your application's stderr to a file when running it:

$ python myapp.py 2>> myerrors.log

If I understand well from your question:

I'd like to capture that action,...

You can test your python script with :

Example:

  • create a bad test.py python script:
import os

print (""_
  • run this python source code:
import subprocess

p = subprocess.Popen(['python', 'test.py'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)

out, err = p.communicate()

print (out, err)

b'' b'  File "/home/mythcat/MonoProiects/test.py", line 2\n    print (""_\n             ^\nSyntaxError: invalid syntax\n'
Related