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

Generate Parenthesis | Intuition + Code | Recursion Tree | Backtracking | Java

Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…

3 months ago

Square Root of Integer

Given an integer A. Compute and return the square root of A. If A is…

1 year ago

Build Array From Permutation

Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…

1 year ago

DSA: Heap

A heap is a specialized tree-based data structure that satisfies the heap property. It is…

2 years ago

DSA: Trie

What is a Trie in DSA? A trie, often known as a prefix tree, is…

2 years ago

Trees: Lowest Common Ancestor

What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…

2 years ago