1

Apologies if this has been answered before.

I am trying to redirect my console output to a "log" file that includes any error messages. Currently I am able to send my print statements to a file using

sys.stdout = open(r'mydir\Log.txt', 'w')

My question is how do I add any error messages that may come up during my code? My script runs overnight and I am planning to have an email sent to myself with this file detailing where the (if any) error occurred, while also keeping the print statements.

Thank you!

5
  • 1
    Check out the docs.python.org/3/howto/logging-cookbook.html Commented Oct 4, 2021 at 16:43
  • In your case, I would look into the 'Logging to multiple destinations' and 'Using file rotation' sections Commented Oct 4, 2021 at 16:45
  • 4
    Probably the best way to do it is by writing your errors to sys.stderr and launch your puthon script with python scriptname.py 2>/path/yo/log/file, or just use the standard logging library Commented Oct 4, 2021 at 16:46
  • You can put that same file object on sys.stderr also. You may end up with some odd intermingling of data. If these all just status messages, start using the logging module instead of print. You'll get much more functionality. Commented Oct 4, 2021 at 16:46
  • great comments, thank you! Commented Oct 4, 2021 at 16:59

1 Answer 1

1

The logging module is what I went with. It works way better.

logging.info('message') was pretty much all I did.

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

Comments

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.