Need to keep a record of application events after the console closes? Use a Logger from Python’s logging module. Retrieve it with logging.getLogger(__name__) for a module-level logger: repeated calls with the same name return the same object, so you can configure it once. Calling the Logger constructor instead creates distinct objects that need separate configuration. section 12.1.1 section 12.1.2
Listing 12.2 Adding a file handler to the logger
logger = logging.getLogger(__name__)
file_handler = logging.FileHandler("taskier.log") #1
logger.addHandler(file_handler) #2
This setup attaches a FileHandler to the module’s logger, directing its records to taskier.log. section 12.1.2
Record an application event
After attaching the file handler, call logger.warning(f"removed the task {task.title} from the database") when a task is removed. For a task titled Laundry, reading the log file shows: removed the task Laundry from the database. Unlike a console printout, the file remains available for later inspection. section 12.1.2
Configure the logger according to which events you need to keep and where you need to see them:
- Set its level with logger.setLevel(logging.WARNING) to capture WARNING, ERROR, and CRITICAL while excluding INFO and DEBUG. The logger checks its threshold before passing a message to a handler; a handler set to DEBUG cannot recover an INFO message rejected by a WARNING-level logger. section 12.2.1 section 12.2.5
- Add a StreamHandler for real-time console feedback alongside a FileHandler for later review. Handlers can have their own levels, allowing finer control over what each destination captures. section 12.1.3 section 12.6
- Avoid attaching the same file handler repeatedly when setup code runs more than once: duplicate handlers can produce duplicate records. Check for existing handlers with hasHandlers before adding one. section 12.1.5
A practical sequence is to retrieve the logger, optionally set its level, attach the handlers you need, and call the method matching each event’s severity. Choose INFO or DEBUG as the logger level when you need more-inclusive records. section 12.2.4




