lxyu
lxyu

Reputation: 2839

how to log background python script's output if some exception is not catched

I have a python script running in background, and I want to log all the exception and output to a log file.

I know to use logging module and try.. catch.. to log exception, but what if I missed some, is there any way to log these exceptions too?

Upvotes: 0

Views: 1827

Answers (2)

Raymond Hettinger
Raymond Hettinger

Reputation: 226256

The usual technique is to use a try/except Exception at the highest level call (the main function). This pretty much assures that you will not have "missed some". Exception matches non-exiting exceptions, so it is casting a broad net.

Upvotes: 2

g.d.d.c
g.d.d.c

Reputation: 47978

You can reassign sys.stdout and sys.stderr to file handles. They'll be available after your python exits if an uncaught exception is encountered. Something like this:

import sys

sys.stdout = open('myOut.txt', 'w')
sys.stderr = open('myErr.txt', 'w')

Upvotes: 0

Related Questions