Last active
January 2, 2016 19:19
-
-
Save miraculixx/8349370 to your computer and use it in GitHub Desktop.
Capture Python's stdout and stderr into a log file. This way you can simply use the print statement without any logger configuration. Great for quick prototyping or maintenance code where you need the log output on a web page instead of in a log file.
This file contains 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
""" | |
Author: patrick dot senti at gmx dot net | |
Use as follows: | |
capture = Capture('mylog.log') | |
print "some log" | |
log = capture.get_log() | |
You can also use it as part of a Django View, like so: | |
capture = Capture('mylog.log') | |
print "some log" | |
return capture.show_log() | |
This will return a HttpResponse object with content_type="text/plain". | |
""" | |
class Capture(object): | |
def __init__(self, name="capture.log"): | |
self.log_name=name | |
self.open_log() | |
def open_log(self): | |
try: | |
self.log = open(os.path.join(settings.TMP_FOLDER, self.log_name), 'w') | |
self.stdout = sys.stdout | |
self.stderr = sys.stderr | |
sys.stdout = self.log | |
sys.stderr = self.log | |
except: | |
raise | |
def close_log(self): | |
try: | |
sys.stdout = self.stdout | |
sys.stderr = self.stderr | |
self.log.close() | |
except: | |
raise | |
def get_log(self): | |
try: | |
self.close_log() | |
self.log = open(os.path.join(settings.TMP_FOLDER, self.log_name), 'r') | |
log = self.log.read() | |
if log: | |
out1 = log | |
else: | |
out1 = "" | |
except Exception as e: | |
out1 = "Capture.get_log: %s" % e | |
return out1 | |
def show_log(self): | |
response = HttpResponse(content_type="text/plain") | |
try: | |
response.write(self.get_log()) | |
return response | |
except Exception as e: | |
response.content("Capture.show_log: %s" % e) | |
raise e |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment