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?

1

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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')

2 Comments

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 - 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.