Course contentsShow
← Python
Lesson 400 of 1,0606. Error Handling and File I/OFree lesson

Directing Logs to Multiple Output Destinations

Learners will configure handlers to simultaneously route diagnostic information to console streams, local files, and remote monitoring services.

In this lesson, you will learn how to configure a single logger to send diagnostic messages to the console, a local file, and a remote service simultaneously.

Why use multiple destinations?

When troubleshooting a complex application, you often need different views of your data. A developer might want to see real-time output in their terminal (console), while an administrator needs a permanent record stored in a log file. Meanwhile, an automated monitoring service requires raw data sent to a remote API to trigger alerts if errors spike. Python’s logging module achieves this using Handlers.

Configuring Multiple Handlers

The core idea is to attach multiple "handlers" to a single logger object. Each handler is responsible for a specific destination. You can think of a logger as a distribution hub: when you call logger.error("Something went wrong!"), the logger sends that message to every handler attached to it.

Here is how you can set up simultaneous output:

import logging

# 1. Create a logger
logger = logging.getLogger("AppLogger")
logger.setLevel(logging.INFO)

# 2. Create console handler
console_handler = logging.StreamHandler()
logger.addHandler(console_handler)

# 3. Create file handler
file_handler = logging.FileHandler("app_log.txt")
logger.addHandler(file_handler)

# 4. Create a custom remote handler (represented as a generic handler)
# In practice, you might use a library to send data to a remote URL
remote_handler = logging.StreamHandler() 
logger.addHandler(remote_handler)

# Now, one message goes everywhere
logger.info("Application started successfully.")

Managing Granularity

You don't have to send everything to every destination. Because each handler is an independent object, you can set different log levels for them. For example, you might set your console_handler to only show WARNING or higher to keep the terminal clean, while the file_handler is set to DEBUG to record every minor event for future auditing. By assigning different Formatter objects to each handler, you can even customize how the message looks—giving the console simple text while providing the remote service with structured JSON.

Key Takeaway: By attaching multiple handler objects to a single logger, you can route the same diagnostic information to diverse destinations—like consoles, files, and remote APIs—simultaneously and with unique levels of detail.