Sub topic 3
Getting started with basicConfig
This chapter assumes you know basic Python syntax and modules, and that you can run a script from a terminal. It also assumes you know what the log levels DEBUG, INFO, WARNING, ERROR and CRITICAL mean.
What basicConfig does
logging.basicConfig() is the quickest way to set up logging for a script. It configures the root logger, which is the top logger that every other logger passes records up to. In one call it can:
- Set the minimum level of the root logger.
- Create a handler, which is the object that sends records to a destination. By default this is a
StreamHandlerthat writes to stderr. - Attach a formatter, which controls how each record looks.
Without any setup, the root logger only shows WARNING and above, and it prints the bare message with no timestamp or logger name. The first example changes the level and the format.
import logging
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
)
logger = logging.getLogger(__name__)
logger.info("Starting %s", "app")
logger.debug("This message is not shown because the level is INFO")The INFO line is printed to stderr and the DEBUG line is dropped. When you run this as a script, %(name)s shows __main__.
Common arguments
| Argument | Purpose |
|---|---|
| `level` | Minimum level for the root logger, such as `logging.INFO` |
| `format` | Format string using `LogRecord` attributes such as `%(levelname)s` |
| `datefmt` | Date format for `%(asctime)s`, in `time.strftime` style |
| `filename` | Write to this file instead of stderr |
| `filemode` | File mode, `"a"` (append) by default |
| `encoding` | File encoding, used together with `filename` |
| `force` | Remove existing root handlers and configure again |
If you pass filename, basicConfig creates a FileHandler instead of a StreamHandler.
import logging
logging.basicConfig(
filename="app.log",
filemode="w",
encoding="utf-8",
level=logging.DEBUG,
format="%(asctime)s %(levelname)-8s %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
logging.getLogger("myapp").debug("Written to app.log")Here filemode="w" overwrites the file on each run. %(levelname)-8s pads the level name to eight characters so the columns line up.
How the call proceeds
Common errors
The most frequent problem is that basicConfig silently does nothing. It only acts when the root logger has no handlers. Two situations cause this:
- Something called
logging.info(),logging.warning()or a similar module-level function earlier. These functions callbasicConfig()for you if the root logger has no handlers, so your later call is ignored. - A framework or notebook environment already attached a handler. Jupyter is a common example.
Call basicConfig once, as early as possible, before any other logging call. If handlers already exist and you need to replace them, pass force=True (Python 3.8 and later).
import logging
logging.warning("This call configures the root logger with defaults")
logging.basicConfig(level=logging.DEBUG) # ignored: handler already exists
logging.basicConfig(level=logging.DEBUG, force=True) # takes effect
logging.debug("Now visible")Two other points to remember:
- Call
basicConfigfrom your entry point, such as themain()function or the top of the script, and never from library code or imported modules. Importing a library should not change an application's logging. basicConfiggives you one handler with one level and format. If you need a console and a file with different levels, you need handlers and loggers, which later chapters cover.
Exercise
A script calls logging.info("start") at the top, then calls logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s"). The "start" message is not printed and later messages ignore the custom format. Why, and how do you fix it?
Show answer
The first logging.info() call runs basicConfig() implicitly with defaults, because the root logger had no handlers. That attaches a handler, so the explicit basicConfig call is ignored. Move the explicit basicConfig call before any logging call, or add force=True to it. The "start" message was also dropped because the default root level is WARNING.