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

Redirecting Standard Streams for Logging

Learners will redirect standard input, output, and error streams to capture application logs and terminal output into persistent storage files.

In this lesson, you will learn how to capture the text your program prints to the console and save it directly into a file for persistent logging.

By default, Python sends output from print() to sys.stdout (Standard Output) and errors to sys.stderr (Standard Error). These streams are usually connected to your terminal window. However, when building robust applications, you often want to keep a record of what happened during execution, even after the terminal is closed. You can achieve this by "redirecting" these streams to a file.

How to Redirect Streams

The sys module provides direct access to these stream objects. You can replace sys.stdout or sys.stderr with any file object opened in write mode. Once you assign an open file to these variables, all subsequent print() calls—or any functions writing to those streams—will automatically route their data into your log file instead of the screen.

import sys
from pathlib import Path

# Define the log file path
log_path = Path("app_logs.txt")

# Open the file and redirect stdout
with open(log_path, "w") as log_file:
    # Save the original stdout so we can restore it later
    original_stdout = sys.stdout
    
    # Redirect stdout to our file
    sys.stdout = log_file
    
    print("This message is now saved to the file instead of the terminal.")
    print("Logging data is useful for debugging!")
    
    # Restore the original stdout
    sys.stdout = original_stdout

print("This message appears back in the terminal.")

Why Redirect?

Redirecting streams is a powerful pattern for capturing "unstructured" logs. For instance, if you call a library function that prints debugging info directly to the screen, you cannot easily intercept it without capturing sys.stdout. By swapping the stream, you force all output from your code (and many third-party libraries) into a persistent file.

Always remember to restore the original stream objects once you are finished. If you don't, your program might behave unexpectedly by failing to print to the user's terminal later in the execution cycle.

Key Takeaway: By assigning an open file object to sys.stdout or sys.stderr, you can programmatically capture and persist terminal output for future auditing and debugging.