Step 2 - Log Level and Log File

The default logging level is set at warning. This can be changed so that we capture more or less information in the log files. In the last example, only the warning returned a result to the console meaning we didn’t see any other log data.

In this step, we are going to change the default log level and save our output into a local log file on the Cloud9 instance. This is done by adding the following line to configure the logging level:

logging.basicConfig(filename='example.log',level=logging.DEBUG)

  • Create a new file called lab_8_step_2_log_level.py and add the following code:
# Import logging
import logging
import json

# Set the log level in the basic configuration.  This means we will capture all our log entries and not just those at Warning or above.
logging.basicConfig(filename='example.log',level=logging.DEBUG)

# This uses a json string as an input
json_string = """
{
    "Input":[
        {
        "Text":"I am learning to code in AWS",
        "SourceLanguageCode":"en",
        "TargetLanguageCode":"fr"
        }
    ]
}
"""

json_input = json.loads(json_string)

# Defines two variables to store the language code from the input.
SourceLanguageCode = json_input['Input'][0]['SourceLanguageCode']
TargetLanguageCode = json_input['Input'][0]['TargetLanguageCode']

# The if statement checks to see if the language code is the same as the source code
if SourceLanguageCode == TargetLanguageCode:
    logging.warning("The SourceLanguageCode is the same as the TargetLanguageCode - stopping") # This will print to the console as the default level is warning
else:
    logging.info("The Source Language and Target Language codes are different - proceeding") # This will not print to the console because it is lower than warning
  • To run the program, enter the following command in the terminal:

    python lab_8_step_2_log_level.py

Test

  1. Run python lab_8_step_2_log_level.py with SourceLanguageCode set to en.
  2. Run python lab_8_step_2_log_level.py with SourceLanguageCode set to fr.
  3. Check that example.log was created in the same directory in Cloud9.
  4. Check that the following text was created in example.log.
INFO:root:The Source Language and Target Language codes are different - proceeding
WARNING:root:The SourceLanguageCode is the same as the TargetLanguageCode - stopping

What we did

  • We set the logging level in logging.basicConfig(filename='example.log,level=logging.DEBUG) to DEBUG. This ensures that any errors which are DEBUG and above will be logged. In effect, this ensures that everything is logged.

  • We told python to create a log file called example.log in Cloud9

What python did

  • Python created a log file called example.log into which it appends any log entries generated by the program.

  • Python set the level to DEBUG. Because both info and warning are higher levels than DEBUG it logged the entries.

In the next step, we are going to add this to our main code.