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!

  • 1
    Check out the https://docs.python.org/3/howto/logging-cookbook.html – rv.kvetch Oct 04 '21 at 16:43
  • In your case, I would look into the 'Logging to multiple destinations' and 'Using file rotation' sections – rv.kvetch Oct 04 '21 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 – ale-cci Oct 04 '21 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. – tdelaney Oct 04 '21 at 16:46
  • great comments, thank you! – smitty_werben_jagerm Oct 04 '21 at 16:59

1 Answers1

1

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

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

Dharman
  • 30,962
  • 25
  • 85
  • 135