Timestamping diagnostics information

Last update on Sept. 26, 2012.

Here's a little python utility to add a timestamp to a text stream. Useful if you have a tool (eg: mtr --raw) that emits information over time, but does not add timing information of its own:

#! /usr/bin/env python

import datetime, sys, optparse

cli_description = "Add a timestamp before each line"

def get_options ():
	parser = optparse.OptionParser ( description=cli_description )
	opts, args = parser.parse_args ()
	if len(args) != 0:
		raise parser.error ( "not expecting arguments" )
	return opts

def timestamp ( infile=sys.stdin, outfile=sys.stdout ):
	while True:
		l = infile.readline()
		if not l: break
		outfile.write ( "[%s] %s" % ( datetime.datetime.utcnow().isoformat(' '), l ) )

if __name__ == "__main__":
	opts = get_options ()
		timestamp ()
	except KeyboardInterrupt:
		print >> sys.stderr, "Interrupted"

Yes, the "optparse" thing is unnecessary here, but I think its a good pattern to get used to typing in each time. The intent is that the meat of the tool can be run from the CLI and be imported into another python program, equally. "optparse" rather than "parseargs" as we still have way too many Python-2.5 installations around here.

Next entry

Previous entry

Similar entries


Comments are closed.


Pingbacks are closed.