Learn

The logging module provides some nifty capabilities to add several handlers to a single logger object. This means that we can easily direct our log messages to multiple streams, such as both a console and a file.

Logging to both a console and file can be useful in cases where we want certain information to go to the console, like debugging information and other log information like errors to write to a file so that we can later search within the file.

We can do this by adding multiple addHandler(hdlr) calls for each handler object. An example of this is shown below:

logger.addHandler(file_handler) logger.addHandler(stream_handler)

Let’s practice with adding multiple handlers and see it in a real program.

Instructions

1.

Create a FileHandler object called file_handler that sends logs to a file called calculator.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.

Create a StreamHandler object called stream_handler that sends logs to the output console. 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.

3.

Uncomment the following last three lines of script.py:

#result = division() #if result == None: # logger.warning("The result value is None!")

Inside the terminal output, execute python3 script.py with the following inputs:

  • Dividend = 6
  • Divisor = 0

View the contents of the calculator.log by finding it in the file explorer. You can find the file explorer by clicking on the folder icon next to script.py. Verify that the output to the console matches the log messages that are inside the calculator.log file. Once you verify this, click Check Work.

Note that there is no output to the console when running this code. All logs are inside the calculator.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?