Created
June 13, 2013 15:28
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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