2

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?

ruohola
  • 21,987
  • 6
  • 62
  • 97
Dariusz
  • 960
  • 13
  • 36
  • 4
    Does this answer your question? [Logging uncaught exceptions in Python](https://stackoverflow.com/questions/6234405/logging-uncaught-exceptions-in-python). Note that the question/answer are for python 2, though modifying for python 3 is easy. – SuperStormer Jan 02 '21 at 22:46
  • You may also want to look into the `logging` module: https://docs.python.org/3/library/logging.html – Sumner Evans Jan 03 '21 at 05:00

2 Answers2

2

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
ruohola
  • 21,987
  • 6
  • 62
  • 97
0

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'
ruohola
  • 21,987
  • 6
  • 62
  • 97