logging.getLogger
- Python course
- Advanced
- Lesson 67/83
- 5 min
Learn to get a logger with logging.getLogger.
logging.getLogger
logging.getLogger(name) returns a logger object. Calls with the same name always return the same object; this lets you categorize logs.
import logging
logger = logging.getLogger("myapp")
print(logger.name) # myappLogger names are usually hierarchical with dots: myapp.db, myapp.api. This lets child loggers inherit from the parent.
Logger hierarchy
Logger names are dot-separated; myapp.db is a child of myapp. The child inherits the level and handler settings of the parent.
parent = logging.getLogger("myapp")
child = logging.getLogger("myapp.db")
print(child.parent.name) # myappThe root logger is obtained with getLogger() (no name); all loggers are attached to it. This hierarchy makes it easy to organize logs in large applications.
Practice Get a logger and print its name
Start with import logging. Get a logger with logger = logging.getLogger("myapp"). Print its name with print(logger.name).
Starter code
# import the logging module
# get a logger named 'myapp'
# print the logger's nameSample solution
import logging
logger = logging.getLogger("myapp")
print(logger.name)Expected output
myapp
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What happens if logging.getLogger("myapp") is called twice?
- Different objects are returned
- The same object is returned Correct answer
- An error is raised
- None is returned
Explanation: Calls with the same name return the same logger.
2 Complete the getLogger call
import logging
logger = logging.____("myapp")
import logging
logger = logging.getLogger("myapp")
Explanation: logging.getLogger('myapp') gets a logger.
3 Match the getLogger concepts
| Term | Meaning |
|---|---|
getLogger |
Gives a logger |
logger.name |
Returns the name |
myapp.db |
Is a child logger |
getLogger() |
Is the root logger |