0

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?

lxyu
  • 2,661
  • 5
  • 23
  • 29
  • possible duplicate of [Python: Temporarily Redirect stdout/stderr](http://stackoverflow.com/questions/6796492/python-temporarily-redirect-stdout-stderr) – g.d.d.c Oct 27 '11 at 03:42

2 Answers2

2

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.

Raymond Hettinger
  • 216,523
  • 63
  • 388
  • 485
0

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')
g.d.d.c
  • 46,865
  • 9
  • 101
  • 111
  • this will not add time on an exception quit, is it? I'm wondering if any way would work as the logging module's behavior. – lxyu Oct 27 '11 at 03:44
  • @lxyu - I ... am not sure what you are asking. This will redirect all of stdout or stderr to files, useful for when you'll be running a script in the background or in some way unattended and want a record of what it outputs. The `logging` module supports the `write(str)` method, which means you could assign an instance of a log to either or both of these. – g.d.d.c Oct 27 '11 at 03:47