Log in from a computer to take this course

You'll need to log in from a computer to start Learn Advanced Python 3. But you can practice or keep up your coding streak with the Codecademy Go app. Download the app to get started.

apple storegoogle store
Learn

A crucial benefit of using the logging module is the ability to format log messages. This allows us to include helpful information with each logged message, including:

  • timestamps
  • the module name
  • the line number
  • and much more.

If no custom formatting is specified, Python uses the default formatting for all log messages:

%(levelname)s:%(name)s:%(message)s
  • %(levelname)s is a string that represents the log level name
  • %(name)s represents the string of the name of the logger
  • %(message)s is the logged message string.

A colon separates each of these strings. Let’s examine the default formatting on a logged message.

import logging import sys logger = logging.getLogger(__name__) stream_handler = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) logger.warning("This is a warning!")

produces the following log message output:

WARNING:script:This is a warning!

Imagine that we want to include a timestamp and line number in our log. We can create a custom formatter object using the logging module’s Formatter class, which accepts the formatted string as the first input value. We can do the following to add in our timestamp and line number formatting:

formatter = logging.Formatter("[%(asctime)s] %(levelname)s:%(name)s:%(lineno)d:%(message)s")

To set this formatter object to our logger, we use the setFormatter(fmt) method where the fmt parameter is the Formatter object. Our revised code will resemble this:

import logging logger = logging.getLogger(__name__) stream_handler = logging.StreamHandler(sys.stdout) formatter = logging.Formatter("[%(asctime)s] %(levelname)s:%(name)s:%(lineno)d:%(message)s") stream_handler.setFormatter(formatter) logger.addHandler(stream_handler) logger.warning("This is a warning!")

which will now produce the following log message output:

[2021-11-04 02:58:51,847] WARNING:script:This is a warning!

The setFormatter method will work on several different types of handler classes, including StreamHandler as seen above and FileHandler. This means that we can set other formatting options for various handlers. For example, if we choose to log to both console and a file, we can have different formatting for the log messages for each one by applying two separate Formatter objects to each handler. This can be useful if we need to, for example, log DEBUG messages to console with more information in each log message than what we need in our written log file.

You can find more information about formatting options can in the Python documentation here.

Instructions

1.

In script.py, we have preloaded a FileHandler object called file_handler. Format the object to match the following:

[%(asctime)s] {%(levelname)s} %(name)s: #%(lineno)d - %(message)s

To do this, create a Formatter object called formatter1. Then set the format of file_handler to the formatter1 object.

Run the program by typing python3 script.py in the terminal and clicking Enter. Click Check Work once the program is complete.

2.

In script.py, we have preloaded a StreamHandler object called stream_handler. Format the object to match the following:

[%(asctime)s] {%(levelname)s} - %(message)s

To do this, create a Formatter object called formatter2. Then set the format of stream_handler to the formatter2 object.

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!")

Run the program by typing python3 script.py in the terminal and clicking Enter. View and verify that the formatted.log file has differently formatted log messages than the console log messages. Once you have done this, click Check Work to move onto the next exercise.

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?