Courses / Monitoring and Logging Practices
1. Log Levels
Different severity levels used in logging to categorize messages.
How It Works
Think of log levels like a traffic light: green means go (info), yellow means caution (warning), and red means stop (error).
Log levels are defined constants in the logging module.
Each message is tagged with a severity level.
Filters can be applied to show only messages of a certain level or higher.
Messages below the set threshold are ignored.
See It
The code sets the logging level to WARNING, so only warning and error messages are displayed. You could try changing the level to INFO to see more messages.
import logging
logging.basicConfig(level=logging.WARNING)
logging.debug("This is a debug message")
logging.info("This is an info message")
logging.warning("This is a warning message")
logging.error("This is an error message")Use It
In a production environment, log levels help manage output verbosity.
import logging
logging.basicConfig(level=logging.ERROR)
def divide(a, b):
try:
return a / b
except ZeroDivisionError:
logging.error("Division by zero error!")
divide(10, 0)Using log levels allows developers to capture critical errors without being overwhelmed by less important messages.
Break It
What will this print?
import logging
logging.basicConfig(level=logging.INFO)
logging.debug("This is a debug message")
logging.info("This is an info message")
logging.warning("This is a warning message")
logging.error("This is an error message")The logging level is set to INFO, which means only messages of that level or higher (INFO, WARNING, ERROR) will be shown; DEBUG messages are ignored.
Change the logging level to DEBUG to see all messages.
import logging
logging.basicConfig(level=logging.DEBUG)
logging.debug("This is a debug message")
logging.info("This is an info message")
logging.warning("This is a warning message")
logging.error("This is an error message")Level Up
Custom Log Levels: Creating custom log levels allows for more granular control over logging output.
Logging to Files: Writing logs to files instead of the console helps in maintaining a persistent log history.
Prove It
Create a logging setup that only records error messages to a file.
Python
Log Levels
Log levels help categorize messages based on their severity in logging.
"I need to filter out less important messages while troubleshooting."
Log levels are predefined categories that indicate the severity of log messages, allowing developers to prioritize issues effectively.
"I need to filter out less important messages while troubleshooting."
Log levels are predefined categories that indicate the severity of log messages, allowing developers to prioritize issues effectively.