Redirect Python ‘print’ output to Logger

You have two options:

  1. Open a logfile and replace sys.stdout with it, not a function:

    log = open("myprog.log", "a")
    sys.stdout = log
    
    >>> print("Hello")
    >>> # nothing is printed because it goes to the log file instead.
    
  2. Replace print with your log function:

    # If you're using python 2.x, uncomment the next line
    #from __future__ import print_function
    print = log.info
    
    >>> print("Hello!")
    >>> # nothing is printed because log.info is called instead of print
    

Leave a Comment