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()
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()
No, it will not write to both.
print()
will write to the console only. One quick note on your original code. I presume you definemessage
somewhere, but the code is still incorrect. You need quotes around thea
in theopen
statement, like this:since I presume you meant to append to the file. Otherwise, you code throws a
NameError
sincea
is 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_logger
function creates a logger object specific to the function in which it's called.The function
f1()
logsDEBUG
level messages and above to a filef1.log
, while writingERROR
level messages and above to the console, with different formatting for each.The function
f2()
, however, logs nothing to the console and only logsWARNING
level messages to its log filef2.log
. Running this script once yields this output on the console:and this output in
f1.log
andf2.log
, respectively:f1.log:
f2.log
No. It writes to file only. You should use
logging
module. See http://docs.python.org/library/logging.html