Skip to main content

Adding Logging to a Python Application

Hands-On Lab

 

Photo of Larry Fritts

Larry Fritts

Python Development Training Architect II

Length

01:00:00

Difficulty

Beginner

Logging is a powerful tool. It can be used for many different functions. For example, it can used in a legal situation as evidence for who has done what while using the application. It can be used to rebuild a database if the database is destroyed without a viable backup. It can also help a developer track down elusive errors when an application has gone to production.

You will need basic Python programming and SQL skills for this lab:

What are Hands-On Labs?

Hands-On Labs are scenario-based learning environments where learners can practice without consequences. Don't compromise a system or waste money on expensive downloads. Practice real-world skills without the real-world risk, no assembly required.

Adding Logging to a Python Application

Introduction

Logging is a powerful tool. It can be used for many different functions. For example, it can used in a legal situation as evidence for who has done what while using the application. It can be used to rebuild a database if the database is destroyed without a viable backup. It can also help a developer track down elusive errors when an application has gone to production.

You will need basic Python programming and SQL skills for this lab:

The Scenario

Atlantic Publishing's Board of Directors asked you to write an application that would allow stock holders to vote, in real time, in an advisory capacity on board issues. You have written a small application that tallies the advisory votes and presents the total to the board. The Board Chairman has asked that you create an audit trail in the event a question is raised about the vote being accurate.

You have the application that tallies the votes. Now you must provide logging to keep track of each vote as it is processed by your app, and give a tally.

Logging In

There are a couple of ways to get in and work with the code. One is to use the credentials provided in the hands-on lab page, log in with SSH, and use a text editor in the terminal.

The other is using VS Code in the browser. If you'd like to go this route, then you will need to navigate to the public IP address of the workstation server (provided in the hands-on lab page) on port 8080 (example: http://PUBLIC_IP:8080).

Add Logging to tally.py

Let's open up tally.py. Here we're going to have some voting data, then associate that with a particular topic. We'll read in some information to figure out what the voting item is, then based on that we'll log out to the appropriate files. There will be a log file for each topic. Our code starts after the return tally line in the several line comment early on in the file.

tally.py:

import logging

def tally_votes(data):
    """
    the example voting data and operations are in the __main__ section
    write code that will ask for user input for item number being voted on
    create a log file named <voting item>.log
    tally votes and log each vote
    using: tally = f"Item: {voting_item} Yes: {yes} No: {no}"
    return tally
    """
    voting_item = input("What is the item number for this vote? ").strip()
    file_name = f"{voting_item}.log"

    logging.basicConfig(
        filename=file_name,
        format='%(asctime)s:%(levelname)s:%(message)s', level=logging.INFO)

    yes = 0
    no = 0
    for vote in data:
        if vote == 'y':
            yes += 1
        else:
            no += 1
        # log vote
        logging.info(vote)

    tally = f"Item: {voting_item} Yes: {yes} No: {no}"

    logging.info(tally)

    return tally

if __name__ == "__main__":
    voting_data = ["y", "n", "y", "y", "y", "n"]
    tally = tally_votes(voting_data)
    print(tally)

Review the Log File

Go ahead and run the script:

python tally.py

Answer the item number, then you'll see results for that item. If you run an ls, you'll now see a log file corresponding to whatever item number you typed. Run cat on that file to see all of the results.

Conclusion

Congratulations! You have shown that you can do basic logging, and have completed the hands-on lab!