Python’s standard-library logging module records application events through loggers and their handlers. Unlike console printouts, records saved to a file remain available for later inspection. section 12.1.1 section 12.1.2
Retrieve a logger with logging.getLogger(name), rather than constructing logging.Logger directly. Repeated calls with the same name return the same logger, so it can be configured once and reused. For a module-level logger, use logging.getLogger(__name__). section 12.1.1
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
After importing logging, attach a FileHandler to save records in taskier.log. Calling logger.warning(message) then writes a warning record to the file. section 12.1.2
A logger can have multiple handlers. Add a StreamHandler alongside the file handler to see events in the console while retaining them in the file. Multiple file handlers can also maintain separate copies; handler levels provide finer control over what each captures. section 12.1.3
Listing 12.4 Using a stream handler with the logger
stream_handler = logging.StreamHandler()
logger.addHandler(stream_handler)
logger.warning("Just a random warning event.")
# output the following: Just a random warning event.
With the file handler already attached, this stream handler sends the same warning to the console and the file. section 12.1.3
Use severity levels to distinguish the importance of events. DEBUG, INFO, WARNING, ERROR, and CRITICAL have increasing numeric values from 10 to 50. Setting the logger to WARNING allows warning, error, and critical records through, while excluding info and debug records. section 12.2.1
Listing 12.5 Logging records at different levels
def logging_messages_all_levels():
logger.critical("--Critical message")
logger.error("--Error message")
logger.warning("--Warning message")
logger.info("--Info message")
logger.debug("--Debug message")
logging_messages_all_levels()
log_records = check_log_content("taskier.log")
print(log_records)
# output the following lines:
removed the task Laundry from the database
Just a random warning event.
--Critical message
--Error message
--Warning message
This example sends one message at each level; with the logger set to WARNING, only the three more serious messages appear in the log. section 12.2.1
Attach a Formatter to a handler to make records easier to inspect. Including the timestamp, level, logger name, and message helps identify important events and correlate them with events outside the application. section 12.2.3
Listing 12.7 Formatting log records for a stream handler
import logging
logger = logging.getLogger(__name__) #1
logger.setLevel(logging.DEBUG) #1
logger.handlers = [] #2
formatter = logging.Formatter("%(asctime)s [%(levelname)s] -
%(name)s - %(message)s") #3
stream_handler = logging.StreamHandler()
stream_handler.setLevel(logging.DEBUG)
stream_handler.setFormatter(formatter) #4
logger.addHandler(stream_handler)
def log_some_records():
logger.info("App is starting")
logger.error("Failed to save the task to the db")
logger.info("Created a task by the user")
logger.critical("Can't update the status of the task")
log_some_records()
# output the following lines:
2022-05-18 10:45:00,900 [INFO] - __main__ - App is starting
2022-05-18 10:45:00,907 [ERROR] - __main__ - Failed to save the
task to the db
2022-05-18 10:45:00,912 [INFO] - __main__ - Created a task by the user
2022-05-18 10:45:00,917 [CRITICAL] - __main__ - Can't update the
status of the task
This stream-handler configuration uses a percent-style format string and sets both logger and handler levels to DEBUG. section 12.2.3



