Simplify Logging in Python with logEZ: A Comprehensive Guide 🚀 [Release 0.1.0]
Are you looking for an easy way to add logging to your Python programs? Do you want a simple yet powerful library that takes care of your logging needs? Introducing logEZ — the logging solution that makes your life easier.
Why Logging Matters
As your applications grow in size and complexity, it becomes increasingly important to understand how they work internally and how each module behaves individually. Logging helps you keep track of each module, its connections, and identify potential issues. With proper logging in place, you can determine where and why your application breaks down — a crucial aspect when developing production-level applications.
In this article, we will explore logEZ — a Python library designed to simplify logging, and walk you through its features and usage.
Getting Started with logEZ
First, install the logEZ library using pip
:
pip install logEZ
The library supports all Python 3 versions, and the logging
library should automatically install.
Once you’ve installed the library, import and initialize the MyLogger()
class:
from logEZ import MyLogger
logger = MyLogger()
With the logger object ready, you can call the logging functions to add logs as needed:
debug(inString: str)
: Log aDEBUG
level message. Accepts a string input.info(inString: str)
: Log anINFO
level message. Accepts a string input.warning(inString: str)
: Log aWARNING
level message. Accepts a string input.error(inString: str, exc_info: Optional[bool] = False)
: Log anERROR
level message. Accepts a string input. Ifexc_info
is set to True, it appends the complete execution information along with the log string.critical(inString: str, exc_info: Optional[bool] = False)
: Log aCRITICAL
level message. Accepts a string input. Ifexc_info
is set to True, it appends the complete execution information along with the log string.
A Sample Application
Now let’s see logEZ in action with a simple example:
from logEZ import MyLogger
import os
logger = MyLogger()
def read_data_from_file(file_path: str):
if not os.path.exists(file_path):
logger.error(f"File not found: {file_path}", exc_info=True)
return None
try:
with open(file_path, 'r') as file:
data = file.readlines()
logger.info(f"Successfully read data from {file_path}")
except Exception as e:
logger.error(f"An error occurred while reading data from {file_path}", exc_info=True)
return None
return data
def calculate_average(numbers):
try:
average = sum(numbers) / len(numbers)
logger.info(f"Calculated average: {average}")
return average
except ZeroDivisionError as e:
logger.error(f"An error occurred while calculating the average", exc_info=True)
return None
except Exception as e:
logger.error(f"An unexpected error occurred while calculating the average", exc_info=True)
return None
def main():
logger.info("Starting the application...")
file_path = "data.txt"
data = read_data_from_file(file_path)
if data is not None:
try:
numbers = [float(x.strip()) for x in data]
except ValueError as e:
logger.critical("Failed to convert data to numbers. Terminating the application...", exc_info=True)
return
average = calculate_average(numbers)
if average is not None:
logger.info(f"The average of the numbers is {average}")
logger.info("Ending the application...")
if __name__ == "__main__":
main()
In this example, the application reads data from a file, converts the data into a list of numbers, and calculates the average of those numbers. The logEZ
library is used to log messages at different logging levels, including info, error, and critical messages. The exc_info
parameter is used to include complete execution information when logging error and critical messages.
When run, the output will look something like this (assuming the file data.txt
does not exist):
01-04-23 15:45:36 - root : INFO : Starting the application...
01-04-23 15:45:36 - root : ERROR : File not found: data.txt
Traceback (most recent call last):
File "example.py", line 6, in read_data_from_file
if not os.path.exists(file_path):
FileNotFoundError: [Errno 2] No such file or directory: 'data.txt'
01-04-23 15:45:36 - root : INFO : Ending the application...
This output shows various log messages, including info and error messages, and includes the traceback for the FileNotFoundError
exception because the exc_info
parameter was set to True
.
Be a Part of the logEZ Community
We are excited to have you join the logEZ community! If you have any suggestions, face any problems, or want to contribute to the project, feel free to raise issues on GitHub or reach out to me via email at gehlotkunal@outlook.com
Project Repo: https://github.com/KunalGehlot/logEZ
PyPi: https://pypi.org/project/logEZ/
Let’s make logging in Python easier together! Happy coding! 🛠️🤝
#PythonLogging #logEZ #PythonDeveloper #Debugging #PythonTips #PythonTricks