Python – Print Logs in a File
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:
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:
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.