Learn

The first step to utilizing the logging module is to import it into our application. We can do this using the following line of code:

import logging

Next, we can obtain our logger object using the getLogger(name) method. This method takes in an optional, single input parameter called name that represents the name of the logger. Calling getLogger() with the same name value returns the same logger object. If we give no name, the root logger is returned.

We recommend using the built-in Python variable __name__ for this value since it will return the current module’s name. This reduces the chance of accidentally reusing a logger name and retrieving the wrong logger object.

Here, we set our logger object to a variable called logger below. We will use it later on in this exercise.

logger = logging.getLogger(__name__)

Next, we need to inform the logger where we want our logged messages to go. To do this, we will use something called a handler. For Python, we will use the logging module’s StreamHandler class. This class handles where our logged messages will output. The StreamHandler class takes in an optional, single input called stream. If we do not supply this value, the logs will direct to sys.stderr. Since we want our output to be direct to the console, we should supply sys.stdout as the stream value. Note that we must import the sys library to reference stdout as the stream value.

import sys stream_handler = logging.StreamHandler(sys.stdout).

Finally, we can now add our stream handler object to the logger. The logging module provides a method called addHandler(hdlr) that adds a specific handler to the logger object. The hdlr input represents the handler object to add, which in our example is the StreamHandler object.

logger.addHandler(stream_handler)

Instructions

1.

Import the logging module and the sys module into our script.py file.

2.

Create a new logger by setting it to a variable called logger. The name of the logger should be the module’s name.

3.

Add a handler to the logger to direct the logged messages to the console. First, create a StreamHandler object called stream_handler. Then, add stream_handler to your logger object.

Note that no output will show in the console just yet until we actually log a message.

Sign up to start coding

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?