Python Logging Variables Data

  • January 26, 2023
  • python
JOIN Clause

In Python, the logging module allows you to log messages to a file or other output destination. You can include variables in the log messages by using string formatting.

We can use a string to describe the event and append the variable data as arguments. Here’s an example:

Example 1:

import logging

x = 5
y = 10
logging.basicConfig(level=logging.DEBUG, filename='example.log')
logging.debug("The values of x and y are: %d and %d", x, y)

In this example, we set up the logging configuration by calling basicConfig() and providing the logging level as logging.DEBUG and the output destination as a file named ‘example.log’. Then we use the debug() method to log the message “The values of x and y are: %d and %d” and the values of x and y as arguments. The message string contains placeholders %d which are replaced by the corresponding variable values when the log message is written.

You can also use the f-string:

logging.debug(f"The values of x and y are: {x} and {y}")

Both of the above methods will log the message “The values of x and y are: 5 and 10” to the ‘example.log’ file.

Example 2:

The following code will log the value of the variable “x” in a message:

import logging

x = 5
logging.debug("The value of x is: %d", x)

You can also use the"The value of x is: {x}") to include the variable data in the log message. The f before the string denotes that it is a f-string, which allows you to directly include the values of variables inside the string by enclosing them in curly braces {}.

It is important to note that the basicConfig() is used to set up the basic configuration of the logging system, such as the logging level and the output destination. And, you can set the level as per your requirement like logging.debug() for debugging purpose.

Note: also read about Python Logging in a file

Follow Me

Please follow me to read my latest post on programming and technology if you like my post.

Leave a Reply

Your email address will not be published. Required fields are marked *