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
If you want to print python logs in a file rather than on the console then we can do so using the basicConfig[]
method by providing filename
and filemode
as parameter.
The format of the message can be specified by using format
parameter in basicConfig[]
method.
Let us take a basic example to print logs to a file rather than on the console. The code snippet is given below:
import logging # first of all import the module
logging.basicConfig[filename='std.log', filemode='w', format='%[name]s - %[levelname]s - %[message]s']
logging.warning['This message will get logged on to a file']
root - ERROR - This message will get logged on to a file
The above output shows how the message will look like but keep in mind it will be written to a file named std.log instead of the console.
In the above code, the filemode
is set to w
, which means the log file is opened in “write mode” each time basicConfig[]
is called, and after each run of the program, it will rewrite the file.
The default configuration for filemode is a
, that is
append, which means that logs will be appended to the log file and adding logs to the existing logs.
Python Logging - Store Logs in a File
There are some basic steps and these are given below:
First of all, simply import the logging module just by writing
import logging
.The second step is to create and configure the logger. To configure logger to store logs in a file, it is mandatory to pass the name of the file in which you want to record the events.
In the third step, the format of the logger can also be set. Note that by default, the file works in append mode but we can change that to write mode if required.
You can also set the level of the logger.
So let's move on to the code now:
#importing the module
import logging
#now we will Create and configure logger
logging.basicConfig[filename="std.log",
format='%[asctime]s %[message]s',
filemode='w']
#Let us Create an object
logger=logging.getLogger[]
#Now we are going to Set the threshold of logger to DEBUG
logger.setLevel[logging.DEBUG]
#some messages to test
logger.debug["This is just a harmless debug message"]
logger.info["This is just an information for you"]
logger.warning["OOPS!!!Its a Warning"]
logger.error["Have you try to divide a number by zero"]
logger.critical["The Internet is not working...."]
The above code will write some messages to file named std.log. If we will open the file then the messages will be written as follows:
2020-06-19 12:48:00,449 - This is just harmless debug message 2020-06-19 12:48:00,449 - This is just an information for you 2020-06-19 12:48:00,449 - OOPS!!!Its a Warning 2020-06-19 12:48:00,449 - Have you try to divide a number by zero 2020-06-19 12:48:00,449 - The Internet is not working...
You can change the format of logs, log level or any other attribute of the LogRecord
along with setting the filename to store logs in a file along with the mode.