No, it will not write to both. print()
will write to the console only. One quick note on your original code. I presume you define message
somewhere, but the code is still incorrect. You need quotes around the a
in the open
statement, like this:
open("logfile.log", "a")
since I presume you meant to append to the file. Otherwise, you code throws a NameError
since a
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:
import inspect
import logging
def function_logger(file_level, console_level = None):
function_name = inspect.stack()[1][3]
logger = logging.getLogger(function_name)
logger.setLevel(logging.DEBUG) #By default, logs all messages
if console_level != None:
ch = logging.StreamHandler() #StreamHandler logs to console
ch.setLevel(console_level)
ch_format = logging.Formatter('%(asctime)s - %(message)s')
ch.setFormatter(ch_format)
logger.addHandler(ch)
fh = logging.FileHandler("{0}.log".format(function_name))
fh.setLevel(file_level)
fh_format = logging.Formatter('%(asctime)s - %(lineno)d - %(levelname)-8s - %(message)s')
fh.setFormatter(fh_format)
logger.addHandler(fh)
return logger
def f1():
f1_logger = function_logger(logging.DEBUG, logging.ERROR)
f1_logger.debug('debug message')
f1_logger.info('info message')
f1_logger.warn('warn message')
f1_logger.error('error message')
f1_logger.critical('critical message')
def f2():
f2_logger = function_logger(logging.WARNING)
f2_logger.debug('debug message')
f2_logger.info('info message')
f2_logger.warn('warn message')
f2_logger.error('error message')
f2_logger.critical('critical message')
def main():
f1()
f2()
logging.shutdown()
main()
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()
logs DEBUG
level messages and above to a file f1.log
, while writing ERROR
level messages and above to the console, with different formatting for each.
The function f2()
, however, logs nothing to the console and only logs WARNING
level messages to its log file f2.log
. Running this script once yields this output on the console:
2012-07-20 10:46:38,950 - f1 - error message
2012-07-20 10:46:38,953 - f1 - critical message
and this output in f1.log
and f2.log
, respectively:
f1.log:
2012-07-20 10:46:38,950 - 26 - DEBUG - debug message
2012-07-20 10:46:38,950 - 27 - INFO - info message
2012-07-20 10:46:38,950 - 28 - WARNING - warn message
2012-07-20 10:46:38,950 - 29 - ERROR - error message
2012-07-20 10:46:38,953 - 30 - CRITICAL - critical message
f2.log
2012-07-20 10:46:38,960 - 36 - WARNING - warn message
2012-07-20 10:46:38,960 - 37 - ERROR - error message
2012-07-20 10:46:38,960 - 38 - CRITICAL - critical message