CodeBlanks Logo Icon CodeBlanks

logging.getLogger

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)  # myapp

Logger 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)  # myapp

The 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

main.py
# import the logging module
# get a logger named 'myapp'
# print the logger's name

Sample solution

main.py
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

Question
import logging

logger = logging.____("myapp")
Answer
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

All lessons in Advanced