Summary - Logging
- Python course
- Advanced
- Lesson 72/83
- 5 min
Combine getLogger, levels and FileHandler to write a logging sample.
Summary - Logging
In this group you learned Python's logging system. getLogger gets a logger, levels set priority, basicConfig is the root config, FileHandler is file output, dictConfig is dict-based configuration.
logging.basicConfig(level=logging.DEBUG,
format="%(levelname)s:%(message)s")
logger = logging.getLogger("myapp")
logger.info("app started")In the final step you will combine all of these to write a logging sample. You can also try writing to both a file and the screen at the same time.
Practice Logging sample
Start with import logging. Call logging.basicConfig(level=logging.DEBUG, format="%(levelname)s:%(message)s"). Get a logger with logger = logging.getLogger("myapp"). Write logger.info("başladı").
Starter code
# import the logging module
# set level DEBUG and format 'level:message' with basicConfig
# get the 'myapp' logger
# write 'başladı' at info levelSample solution
import logging
logging.basicConfig(level=logging.DEBUG, format="%(levelname)s:%(message)s")
logger = logging.getLogger("myapp")
logger.info("başladı")Expected output
INFO:başladı
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which one writes logs to a file?
- FileHandler Correct answer
- getLogger
- StreamHandler
- basicConfig
Explanation: FileHandler writes logs to a file.
2 Match the group tools
| Term | Meaning |
|---|---|
getLogger |
Gives a logger |
logging.DEBUG |
Lowest level |
basicConfig |
Root config |
FileHandler |
Writes to file |