Learn

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.

Writing logs to a saved file makes our logs persistable after program execution, and it allows the log file to be searched or ingested into other applications like Splunk or an ELK Stack.

To write logs to a saved file, we can use the logging module class FileHandler(filename). The 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.

Instructions

1.

Create a 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.

2.

Uncomment the 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.

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?