Up until now, we have used the console for our logged messages. The downside to this is that the logged messages are lost once the execution of the application finishes. There is another helpful stream that we can use to direct our logged messages: files.
To write logs to a saved file, we can use the
logging module class
filename initialization parameter is a string value that represents the filename for the written log file.
Similarly to the
StreamHandler, we can add the
FileHandler object to the logger by using the
addHandler(hdlr) method as shown below:
file_handler = logging.FileHandler("my_program.log") logger.addHandler(file_handler)
We can practice more with adding a file handler to our logger now.
FileHandler object called
file_handler that sends logs to a file called output.log. Add this handler to the
logger object. Make sure to leave the last three lines of your program commented out for now.
Run the program by typing
python3 script.py in the terminal and clicking Enter. Click Check Work once the program is complete.
result = division() line. Inside the terminal output, execute
python3 script.py with the following inputs:
- Dividend = 6
- Divisor = 3
View the contents of the output.log by finding it in the file explorer. You can find the file explorer by clicking on the folder icon next to script.py. Once you see the contents of output.log, click Check Work.
Note that there is no output to the console when running this code. All logs are inside the ouput.log file.