Logging levels and basicConfig

RoadmapsPython

Overview

Python's `logging` module replaces `print()` for production code. It categorizes messages into five severity levels, in increasing order of seriousness: DEBUG, INFO, WARNING, ERROR, CRITICAL. import logging logging.basicConfig(level=logging.INFO) logging.debug('Hidden') # below INFO -- not shown logging.info('Visible') # shown logging.warning('Also shown') `logging.basicConfig()` configures the root logger, setting the minimum level to display and the format of the output — only messages at that level or higher print. By default, before you call `basicConfig()`, the logging level is WARNING, meaning DEBUG and INFO messages are silently ignored.

Unlike `print()`, logging gives you a dial to control output volume without changing code (e.g., hiding DEBUG logs in production). It also automatically includes metadata like timestamps and module names.

Where used: Web servers (Django/FastAPI), Data pipelines, CLI tools

Why learn this

Code walkthrough

import logging

logging.basicConfig(
  level=logging.INFO,
  format='%(levelname)s - %(message)s'
)

logging.debug('Hidden')
logging.info('Visible')

Focus: level=logging.INFO,

Aha moment

import logging

logging.basicConfig(level=logging.INFO)
logging.basicConfig(level=logging.DEBUG)

logging.debug('Can you see me?')

Prediction: Will the debug message be printed?

Common guess: Yes, because the level was changed to DEBUG.

It won't print. `basicConfig()` only works the FIRST time it is called. The second call does nothing, so the level remains INFO.

Common mistakes

Glossary

severity levels
Categories that indicate how serious or important a log message is, e.g. `logging.INFO` for general updates or `logging.CRITICAL` for system failures.
verbosity
The amount of detail or the number of messages a program outputs, e.g. setting `level=logging.DEBUG` is high verbosity, `level=logging.ERROR` is low verbosity.

Recall questions

Understanding checks

What is printed to the console (ignoring format metadata)?

ERROR:root:B CRITICAL:root:C

The level is set to ERROR. WARNING is below ERROR, so 'A' is ignored. ERROR and CRITICAL are high enough to be printed.

What is printed to the console (assuming fresh execution)?

WARNING:root:World

Because no configuration was explicitly set, the default level is WARNING. The INFO message is discarded.

Practice tasks

Configure Logging Level

Given this code, modify the `basicConfig` call so that ONLY 'Critical issue' is printed.

Challenge

Force Configuration

Write a script that first calls `basicConfig` with INFO level, then uses `basicConfig` again to change the level to DEBUG by passing `force=True`, and finally prints a debug message 'Testing'.

Continue learning

Previous: Defining functions and return values

Return to Python Roadmap