Sub topic 3
Getting started with basicConfig
This chapter covers logging.basicConfig(), the one-call setup for scripts and small programs. It assumes you can read basic Python, run scripts from a terminal, and know that logging has levels such as DEBUG and INFO. Loggers, handlers, and formatters get their own chapters. Here you only need to know that basicConfig creates one handler and attaches it to the root logger.
What basicConfig does
Without configuration, Python's logging module shows only WARNING and above, and it prints the bare message with no timestamp or level. basicConfig changes this in one call. It does three things:
- Creates a handler. By default this is a
StreamHandlerwriting tosys.stderr. If you passfilename, it is aFileHandler. - Gives that handler a formatter built from your
format,datefmt, andstylearguments. - Adds the handler to the root logger and sets the root logger's level.
Every logger in your program passes its records up to the root logger by default, so this one handler receives records from all modules. The hierarchy has its own chapter.
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 message appears on stderr with a timestamp, level, and logger name. The DEBUG message is dropped, because its level is below the root logger's threshold.
Notice that the message is written as "Starting %s" with the value passed as a separate argument. Do not build the string yourself with an f-string. The logging module only does the formatting if the record is actually emitted, so a suppressed DEBUG call costs almost nothing.
The defaults
If you call basicConfig() with no arguments, you get:
- Level: WARNING.
- Format:
%(levelname)s:%(name)s:%(message)s, for exampleWARNING:myapp:disk almost full. - Destination: stderr.
Keyword arguments
| Argument | Meaning |
|---|---|
| `level` | Root logger level. Accepts `logging.INFO` or the string `"INFO"`. |
| `format` | Format string for each line, using LogRecord attributes such as `%(levelname)s`. |
| `datefmt` | `strftime`-style format for `%(asctime)s`. |
| `style` | `"%"` (default), `"{"`, or `"$"`. It selects the style of the `format` string. |
| `filename` | Log to this file instead of stderr. |
| `filemode` | Mode used to open the file. Default `"a"` (append). |
| `encoding` | Encoding for the file (Python 3.9 and later). |
| `stream` | An existing stream, such as `sys.stdout`, to write to. |
| `handlers` | A list of ready-made handlers. |
| `force` | Remove and close existing root handlers first (Python 3.8 and later). |
Some combinations are invalid. filename and stream cannot be used together. Neither can be combined with handlers. Each conflict raises ValueError. Unknown keyword arguments also raise ValueError.
A more complete example
This version uses a custom date format, left-aligned level names, and the { style:
import logging
import sys
logging.basicConfig(
level=logging.DEBUG,
stream=sys.stdout,
style="{",
format="{asctime} {levelname:<8} {name}: {message}",
datefmt="%Y-%m-%d %H:%M:%S",
)
log = logging.getLogger("demo")
log.debug("Connecting to %s", "localhost")
log.warning("Retry %d of %d", 2, 5)The style argument only affects the format string. Your log calls still use %s placeholders for arguments.
Logging to a file
import logging
logging.basicConfig(
filename="app.log",
filemode="w",
encoding="utf-8",
level=logging.INFO,
format="%(asctime)s %(levelname)s %(message)s",
)
logging.info("Written to app.log, not to the terminal")With filemode="w" the file is truncated each run. The default "a" appends, which is usually what you want for logs. If you need both the console and a file, use the handlers argument:
import logging
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
handlers=[
logging.StreamHandler(),
logging.FileHandler("app.log", encoding="utf-8"),
],
)
logging.getLogger("demo").info("Goes to stderr and to app.log")Handlers you pass in that have no formatter yet receive the one built from format and datefmt. Handlers that already have a formatter keep it.
The silent no-op
The most common basicConfig surprise is that it does nothing if the root logger already has handlers. This is deliberate, so that the first configuration wins. The second call below is ignored without any error:
import logging
logging.basicConfig(level=logging.INFO)
logging.basicConfig(level=logging.DEBUG) # ignored: root already has a handler
print(logging.getLogger().level == logging.INFO)
logging.getLogger("demo").debug("Not shown")This prints True, and the DEBUG message does not appear. To reconfigure, pass force=True, which removes and closes the existing root handlers first:
import logging
logging.basicConfig(level=logging.INFO)
logging.basicConfig(level=logging.DEBUG, force=True)
logging.getLogger("demo").debug("Shown now")The flow is summarized below.
Implicit configuration
The module-level helpers logging.debug(), logging.info(), logging.warning(), logging.error(), and logging.critical() call basicConfig() with no arguments if the root logger has no handlers. That has two consequences:
- A bare
logging.info("hi")at the top of a script prints nothing, because the implicit setup uses level WARNING. - If you call
logging.warning()before your ownbasicConfig(level=...), the implicit call has already added a handler, and your later call is a no-op.
Always call basicConfig before any log call, ideally once, near the entry point of the program.
Calls on a named logger, such as logging.getLogger("x").warning(...), do not trigger this automatic setup. If nothing is configured, Python uses a last-resort handler that prints WARNING and above to stderr as the bare message. INFO and DEBUG are dropped.
Where to call it
Call basicConfig once, in the code that starts your program, for example under if __name__ == "__main__": or in a main() function. Do not call it at import time in a module that others import. Library code should not configure the root logger at all, because it overrides the application's choices or silently does nothing. The library chapter covers this.
Other mistakes to watch for:
- Setting the level on a handler you passed in and expecting
level=to change it. Thelevelargument sets only the root logger's level. A handler's own level is separate. - Expecting
basicConfigto configure a named logger. It always targets the root logger. - Forgetting
encodingwhen logging non-ASCII text to a file. On some platforms the default is not UTF-8. - Using
force=Truein library code, which removes handlers the application installed.
When to move beyond basicConfig
basicConfig is enough when one format and one or two destinations cover your needs. It cannot give different handlers different levels, add filters, or set levels on specific named loggers. For that you create handlers yourself or use dictConfig, both covered in later chapters.
Exercise
A script starts with logging.info("starting"), then later calls logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s"), then logs logging.info("working"). What is printed, and why? How do you fix it?
Show answer
Nothing is printed. The first logging.info call finds no root handlers, so it runs basicConfig() implicitly with the default level WARNING. That call adds a handler, so the explicit basicConfig later is a no-op, and the root level stays at WARNING. Both INFO messages are dropped. The fix is to call basicConfig before any logging call, or to pass force=True to the explicit call.
Exercise
Write a basicConfig call that logs DEBUG and above to both stderr and a UTF-8 file named run.log, with the format time level message, where the time uses %H:%M:%S.
Show answer
logging.basicConfig(level=logging.DEBUG, format="%(asctime)s %(levelname)s %(message)s", datefmt="%H:%M:%S", handlers=[logging.StreamHandler(), logging.FileHandler("run.log", encoding="utf-8")]). The handlers list is used because filename alone would send output only to the file. Do not pass filename or stream with handlers, or ValueError is raised.