Step 3 - Add logging to our code

In this step add logging to our main code, building on the previous step and labs. This will set the default level to warning and output the logs to a file example.log

  • Create a new file called lab_8_step_3_logging.py and add the following code.
# Standard Imports
import argparse
import json

# 3rd Party Imports
import boto3

# Arguments
parser = argparse.ArgumentParser(description="Provides translation  between one source language and another of the same set of languages.")
parser.add_argument(
    '--file',
    dest='filename',
    help="The path to the input file. The file should be valid json",
    required=True
    )

args = parser.parse_args()

# Functions

# Open the input file to get the json.
def open_input():
    with open(args.filename) as file_object:
        contents = json.load(file_object)
        return contents['Input']

# Boto3 function to use Amazon to translate the text and only return the Translated Text
def translate_text(**kwargs):
    client = boto3.client('translate')
    response = client.translate_text(**kwargs)
    print(response['TranslatedText'])

# Add a Loop to iterate over the json file.
def translate_loop():
    input_text = open_input()
    for item in input_text:
        if input_validation(item) == True:
            translate_text(**item)
        else:
            raise SystemError

# Add our input validation as a function here.
def input_validation(item):
    languages = ["af","sq","am","ar","az","bn","bs","bg","zh","zh-TW","hr","cs","da","fa-AF",
                "nl","en","et","fi","fr","fr-CA","ka","de","el","ha","he","hi","hu","id","it",
                "ja","ko","lv","ms","no","fa","ps","pl","pt","ro","ru","sr","sk","sl","so","es",
                "sw","sv","tl","ta","th","tr","uk","ur","vi"
                ]
    json_input=item
    SourceLanguageCode = json_input['SourceLanguageCode']
    TargetLanguageCode = json_input['TargetLanguageCode']

    if SourceLanguageCode == TargetLanguageCode:
        print("The SourceLanguageCode is the same as the TargetLanguageCode - nothing to do")
        return False
    elif SourceLanguageCode not in languages and TargetLanguageCode not in languages:
        print("Neither the SourceLanguageCode and TargetLanguageCode are valid - stopping")
        return False
    elif SourceLanguageCode not in languages:
        print("The SourceLanguageCode is not valid - stopping")
        return False
    elif TargetLanguageCode not in languages:
        print("The TargetLanguageCode is not valid - stopping")
        return False
    elif SourceLanguageCode in languages and TargetLanguageCode in languages:
        print("The SourceLanguageCode and TargetLanguageCode are valid - proceeding")
        return True
    else:
        print("There is an issue")
        return False

# Main Function - use to call other functions
def main():
    translate_loop()

if __name__ == "__main__":
    main()

Modify your code to add logging to your code. Refer to the previous step if you get stuck.

  1. Import logging.

  2. Set the default log level to debug and the log file to translate.log.

  3. Amend the if-elif-else statements to use logging with the warning, debug and info levels.

  4. Run the code and conduct tests for each scenario.

  5. Check the log file to ensure your code is logging correctly.

  • To run the program, enter the following command in the terminal:

    python lab_8_step_3_logging.py --file translate_input.json

Check Your Code

Was the output of the log file what you expected? What else has been added?

What did you do?

  1. You imported logging into your code.

  2. You set the default level to debug to log everything.

  3. You sent the output to a local file called translate.log

What did python do?

  1. Python has logged every event including botocore events when using the Amazon Translate service.

Verbose logging using debug is good when you are in non-production environments, but you would want to set the default level to warning in production to only capture important events.