Skip to main content

How to Log a Warning in Python with logger.warning

· 3 min read
Jagdish Kumawat
Founder @ Dewiride

Some problems don't stop a program but still deserve a note: a missing optional file, a setting that fell back to its default. That's what a warning is for. logger.warning logs one, and by default it shows even when routine messages don't. This guide logs an info message and a warning, with real output from Python 3.15.2.

Syntax​

Syntax
logger.warning(<message>)
PartWhat it means
loggerA logger from logging.getLogger(<name>)
<message>The text of the warning

Python's logging reference: "Logs a message with level WARNING on this logger." Its logging HOWTO: "The default level is WARNING, which means that only events of this severity and higher will be tracked, unless the logging package is configured to do otherwise."

Prerequisites​

  • uv and Python. This guide uses uv 0.13.10 with Python 3.15.2, in a project made with uv init.

Step 1: Write the Script​

basicConfig sets the format: the level, the logger's name and the message.

warn.py
import logging

logging.basicConfig(format="%(levelname)s %(name)s: %(message)s")
logger = logging.getLogger("backup")

logger.info("Starting the backup")
logger.warning("No database found, so nothing was backed up")

The warn.py script in a macOS-style code window: basicConfig with a levelname, name and message format, a logger named backup, then logger.info and logger.warning.

Step 2: Run It​

Terminal
uv run python warn.py
Output
WARNING backup: No database found, so nothing was backed up

The script's output in a terminal: WARNING backup: No database found, so nothing was backed up.

Only the warning appeared. The info message is below the default level, WARNING, so it was dropped.

Common Mistakes​

MistakeWhat happensDo this instead
Logging routine progress with warningReal warnings get lost among themUse info for progress, warning for things worth a look
Using logger.warnThe reference: "There is an obsolete method warn which is functionally identical to warning. As warn is deprecated, please do not use it"Use logger.warning

Troubleshooting​

SymptomLikely causeFix
Info messages don't appearThe level is WARNING, the defaultPass level=logging.INFO to basicConfig: then both lines printed, INFO backup: Starting the backup first

FAQ​

Where do the messages go?​

basicConfig sends them to standard error, the terminal's error stream, so they stay separate from what the program prints as its result.

What comes after warning?​

error and critical, for problems that stop part or all of the work.

Conclusion​

logger.warning("No database found, so nothing was backed up") printed WARNING backup: …, while logger.info printed nothing until the level was lowered to INFO.

Additional Resources​