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:
# Import logging
# 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.
# This uses a json string as an input
json_string = """
"Text":"I am learning to code in AWS",
json_input = json.loads(json_string)
# Defines two variables to store the language code from the input.
SourceLanguageCode = json_input['Input']['SourceLanguageCode']
TargetLanguageCode = json_input['Input']['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
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:
INFO:root:The Source Language and Target Language codes are different - proceeding
WARNING:root:The SourceLanguageCode is the same as the TargetLanguageCode - stopping
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
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.