Reputation: 291
I'm using Python 2.7 and pyinstaller to create a program. My program uses "print" to display the current progress of my program. What I want is for my program to create an error log in the event of an error, which will show the various statements that have printed to the screen so that I can see it's progress. Below is a simple program that will cause a zerodivisionerror:
import os
os.chdir("C:")
logname="Error 30032014 1832"
def subroutine():
print "Subroutine started"
print "Stage1 is complete"
print "Stage2 is complete"
a=1
b=0
c=a/b
subroutine()
This is the result:
Subroutine started
Stage1 is complete
Stage2 is complete
Traceback (most recent call last):
File "C:/Users/Joseph/Desktop/a.py", line 8, in <module>
subroutine()
File "C:/Users/Joseph/Desktop/a.py", line 7, in subroutine
c=a/b
ZeroDivisionError: integer division or modulo by zero
I want a textfile with the name logname (or if the name can be generated automatically with the date and time) to be generated displaying the above displayed information so that I can examine the error.
Upvotes: 0
Views: 470
Reputation: 3193
If you want your print
statements to print to the log file, you can redirect the output stream to your log file:
import sys
stdout = sys.stdout #save the original stdout stream
log_file = open("C:/logfile.log", 'w')
sys.stdout = log_file
print "This happened" #goes to the log file
print "And that too!"
You can do the same with sys.stderr
to redirect your exceptions to the writable. But of course, logging is better suited to that purpose.
Upvotes: 0
Reputation: 42208
Python has built in logging facilities, which you should use for logging.
Here is a link to the docs for logging library: https://docs.python.org/2/library/logging.html
Here is example from documentation on how it is used:
import logging
logging.warning('Watch out!') # will print a message to the console
logging.info('I told you so') # will not print anything
Upvotes: 1