0
0
PythonHow-ToBeginner · 3 min read

How to Set Logging Level in Python: Simple Guide

In Python, you set the logging level using logging.basicConfig(level=LEVEL) where LEVEL is one of the predefined levels like DEBUG, INFO, WARNING, ERROR, or CRITICAL. This controls which messages are shown based on their importance.
📐

Syntax

The basic syntax to set the logging level is:

  • logging.basicConfig(level=LEVEL): Configures the root logger to show messages at or above the specified LEVEL.
  • LEVEL can be DEBUG, INFO, WARNING, ERROR, or CRITICAL.

This sets the minimum severity of messages that will be displayed.

python
import logging

logging.basicConfig(level=logging.INFO)
💻

Example

This example shows how to set the logging level to WARNING. Only messages with level WARNING or higher will be printed.

python
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')
logging.critical('This is a critical message')
Output
WARNING:root:This is a warning message ERROR:root:This is an error message CRITICAL:root:This is a critical message
⚠️

Common Pitfalls

Common mistakes when setting logging levels include:

  • Calling logging.basicConfig() multiple times has no effect after the first call.
  • Not setting the level properly, so messages you expect to see are hidden.
  • Confusing logger levels with handler levels when using advanced logging setups.

Always set the logging level once at the start of your program.

python
import logging

# Wrong: calling basicConfig twice does nothing the second time
logging.basicConfig(level=logging.ERROR)
logging.basicConfig(level=logging.DEBUG)  # This call is ignored

logging.debug('Debug message')  # Won't show
logging.error('Error message')  # Will show
Output
ERROR:root:Error message
📊

Quick Reference

Logging LevelNumeric ValueDescription
DEBUG10Detailed information, typically of interest only when diagnosing problems.
INFO20Confirmation that things are working as expected.
WARNING30An indication that something unexpected happened, or indicative of some problem in the near future.
ERROR40Due to a more serious problem, the software has not been able to perform some function.
CRITICAL50A very serious error, indicating that the program itself may be unable to continue running.

Key Takeaways

Use logging.basicConfig(level=LEVEL) to set the minimum logging level.
Only messages at or above the set level will be shown.
Set the logging level once at the start of your program.
Common levels are DEBUG, INFO, WARNING, ERROR, and CRITICAL.
Calling basicConfig multiple times has no effect after the first call.