Categories: python

Python Logging Variables Data

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.basicConfig(level=logging.DEBUG)
logging.debug("The value of x is: %d", x)

You can also use the logging.info(f"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.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Recent Posts

Select a Random Element from a Stream

You are given a stream of elements that is too large to fit into memory.…

16 hours ago

Estimate π Using Monte Carlo Method

The formula for the area of a circle is given by πr². Use the Monte…

3 weeks ago

Longest Substring with K Distinct Characters

Given an integer k and a string s, write a function to determine the length…

3 weeks ago

Staircase Climbing Ways

There is a staircase with N steps, and you can ascend either 1 step or…

3 weeks ago

Autocomplete System Implementation

Build an autocomplete system that, given a query string s and a set of possible…

4 weeks ago

Job Scheduler Implementation

Design a job scheduler that accepts a function f and an integer n. The scheduler…

4 weeks ago