basicConfig
- Python course
- Advanced
- Lesson 69/83
- 5 min
Learn configuration with logging.basicConfig.
basicConfig
logging.basicConfig configures the root logger in one line. With level you set the minimum level, with format the message format, with filename a file output.
import logging
logging.basicConfig(
level=logging.DEBUG,
format="%(levelname)s:%(message)s",
)
logger = logging.getLogger("myapp")
logger.info("merhaba") # INFO:merhababasicConfig works only on the first call; later calls are ignored. So it is called once at program start.
Format placeholders
The format string shapes the message with placeholders. Common ones: %(asctime)s (time), %(levelname)s (level name), %(name)s (logger name), %(message)s (message).
format="%(asctime)s %(levelname)s %(message)s"
# 2025-01-01 12:00:00 INFO merhabaA good format makes logs readable; time and level are usually important. Using a consistent format in long apps makes logs easier to scan.
Practice Log with basicConfig
Start with import logging. Call logging.basicConfig(level=logging.DEBUG, format="%(levelname)s:%(message)s"). Get a logger with logger = logging.getLogger("myapp"). Write info with logger.info("merhaba").
Starter code
# import the logging module
# set level DEBUG and format 'level:message' with basicConfig
# get the 'myapp' logger
# write 'merhaba' at info levelSample solution
import logging
logging.basicConfig(level=logging.DEBUG, format="%(levelname)s:%(message)s")
logger = logging.getLogger("myapp")
logger.info("merhaba")Expected output
INFO:merhaba
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the basicConfig concepts
| Term | Meaning |
|---|---|
level |
Sets the minimum level |
format |
Sets the message format |
filename |
Writes to a file |
%(levelname)s |
Level name placeholder |
2 What does the format parameter do in basicConfig?
- Sets the level
- Sets the message format Correct answer
- Sets the logger name
- Sets the file name
Explanation: The format parameter sets the message format with placeholders.
3 Complete the basicConfig call
import logging
logging.basicConfig(
level=logging.____,
format="%(levelname)s:%(message)s",
)
import logging
logging.basicConfig(
level=logging.DEBUG,
format="%(levelname)s:%(message)s",
)
Explanation: level=logging.DEBUG sets the minimum level.