Skip to content

Instantly share code, notes, and snippets.

@mdwhatcott
Created June 13, 2013 15:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mdwhatcott/5774613 to your computer and use it in GitHub Desktop.
Save mdwhatcott/5774613 to your computer and use it in GitHub Desktop.
Write log messages to the console (sys.stdout) and to a log file, all managed as a context manager.
import sys
class Logger(object):
"""
Write log messages to the console (sys.stdout) and to a log file,
all managed as a context manager:
>>> with Logger('log_file.txt'):
... print "Hello, World!" # goes to stdout and to the log file
...
Hello, World!
>>> print open('log_file.txt').read()
Hello, World!
"""
def write(self, message):
self.console.write(message)
self.console.flush()
self.log_file.write(message)
self.log_file.flush()
def close(self):
self.console.flush()
self.log_file.flush()
self.log_file.close()
def __init__(self, log_file):
self.console = sys.stdout
self.log_file_name = log_file
self.log_file = None
def __enter__(self):
self.log_file = open(self.log_file_name, 'w')
sys.stdout = self
return self
def __exit__(self, *args):
self.close()
sys.stdout = self.console
return not any(args)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment