Logging Varriable Data

Variable Data

When creating logs it will be useful if we had the option to use variables to make a more meaningful log record. While we can create variables that hold our string, we can also create logs that directly access a variable we require.

import logging

user_name = "Christopher"

logging.warning("%s encountered a warning message", user_name)

This is the output:

We created a variable to store the user’s name. ‘%s’ is used to add one string within another string, and it also automatically converts it to a string. If we want to add more strings, we need to exact number ‘%s’ operators and in the correct position as well.

It is also not necessary to use the ‘%s” operator, we can also use f strings.

import logging

threat_type = "Firewall Systems"

logging.critical(f"{threat_type} has been breached")

This will give us the output:

Let’s consider an example of this:

import logging, time

custom_log_format = "%(levelname)s: => %(message)s"

logging.basicConfig(
    level=logging.DEBUG,  # specifying the minimum severity level
    filename="logFile.log",  # name of the file to write our log on to
    filemode="w",  # file opening mode
    format=custom_log_format  # format the output
)

# Starting counter
start_time = time.time()

# Raise an error
logging.critical("Error occurred!")

# End counter
run_time = time.time() - start_time

logging.info(f"The program crashed in {round(run_time, 3)} seconds.")

When we run this, the code will generate a text file with the following text:

What have we learned?

  • How can we create a log that uses variables?
  • What is the use of the “%s” operator?
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments