Does this code write to both a log file and the console at the same time?
logFile = open("logfile.log",a)
print >>logFile,message
logFile.close()
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
No, it will not write to both.
print()will write to the console only. One quick note on your original code. I presume you definemessagesomewhere, but the code is still incorrect. You need quotes around theain theopenstatement, like this:since I presume you meant to append to the file. Otherwise, you code throws a
NameErrorsinceais not a defined variable.However, as others have said, you should strongly consider using the logging module. Here is a simple example of how to write to both the console and a log file. The code is partially derived from here and here:
Since logger objects can have more than one handler, we can create multiple handlers that write to different places. In my code, the
function_loggerfunction creates a logger object specific to the function in which it’s called.The function
f1()logsDEBUGlevel messages and above to a filef1.log, while writingERRORlevel messages and above to the console, with different formatting for each.The function
f2(), however, logs nothing to the console and only logsWARNINGlevel messages to its log filef2.log. Running this script once yields this output on the console:and this output in
f1.logandf2.log, respectively:f1.log:
f2.log