Skip to content

Instantly share code, notes, and snippets.

@nodakai
Created November 1, 2016 10:21
Show Gist options
  • Save nodakai/4332a8659a7f9058e22fc8639f4e472b to your computer and use it in GitHub Desktop.
Save nodakai/4332a8659a7f9058e22fc8639f4e472b to your computer and use it in GitHub Desktop.
Wrap stdout to add timestamps
n = datetime.datetime.now
class Wrapper(object):
def __init__(self, out, severity):
self.out = out
self.severity = severity
self.remaining = None
self.remaining_ts = None
def _write(self, t, line):
print("{0} {1} {2}".format(t, self.severity, line), file=self.out)
def write(self, s):
if not s:
return
t = n().strftime('%Y-%m-%d %H:%M:%S.%f')
lines = s.split('\n') # guaranteed to be non-empty
last = lines.pop()
if not lines:
if self.remaining is not None:
self.remaining += last
else:
self.remaining = last
self.remaining_ts = t
return
if self.remaining is not None:
self._write(self.remaining_ts, self.remaining + lines.pop(0))
self.remaining = self.remaining_ts = None
if last:
self.remaining = last
self.remaining_ts = t
for line in lines:
self._write(t, line)
def close(self):
if self.remaining:
self._write(self.remaining_ts, self.remaining)
self.out.close()
def __del__(self):
self.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment