In Python, the logging module provides several classes and functions to help you log messages in your code. We can create our own logger by instantiating the logging.Logger class and giving it a unique name. This is useful when your application has multiple modules, as you can use separate loggers for each module to keep the log messages separate and organized. Here are a few of the most commonly used ones:
Here are a few examples of commonly used classes in the logging module:
These classes can be used to configure the logger, and to customize the log messages, format, and output destinations.
Example:
import logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
file_handler = logging.FileHandler('example.log')
file_handler.setLevel(logging.ERROR)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
logger.debug("This is a debug message")
logger.error("This is an error message")
In the above example, a logger is created with the name of the module. Then the level of the logger is set to debug and a file handler is added with the level of error. The Formatter class is used to format the log message and set to the file handler.
In addition to these classes and functions, the logging module also provides several other features, such as the ability to configure loggers using configuration files, and the ability to add custom handlers to control where log messages are sent.
Note: also read about Python Logging Variables Data
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
Staying up to the mark is what defines me. Hi all! I’m Rabecca Fatima a keen learner, great enthusiast, ready to take new challenges as stepping stones towards flying colors.
You are given a stream of elements that is too large to fit into memory.…
The formula for the area of a circle is given by πr². Use the Monte…
Given an integer k and a string s, write a function to determine the length…
There is a staircase with N steps, and you can ascend either 1 step or…
Build an autocomplete system that, given a query string s and a set of possible…
Design a job scheduler that accepts a function f and an integer n. The scheduler…