Skip to content

Instantly share code, notes, and snippets.

@drizzd
Created July 6, 2018 08:13
Show Gist options
  • Save drizzd/c21b56996efeb3865b05f85235eca1a7 to your computer and use it in GitHub Desktop.
Save drizzd/c21b56996efeb3865b05f85235eca1a7 to your computer and use it in GitHub Desktop.
Timestamper

In the meantime I am using the following Python 2.7 script to add timestamps in the style of the Python logging module. Make sure to use Python's -u Option to disable output buffering.

$ python -u timestamper.py sh -c 'echo hey; sleep 1; echo ho'
2017-05-08 09:17:56.517 hey
2017-05-08 09:17:57.520 ho
# .gitlab-ci.yml
myjob:
    script: "python -u timestamper.py ./myJob.sh"
# timestamper.py
import datetime
import sys

def time():
    now = datetime.datetime.now()
    dateAndTime = now.strftime('%Y-%m-%d %H:%M:%S')
    millisecond = now.microsecond/1000
    if millisecond is None:
        millisecondText = 'NNN'
    else:
        millisecondText = '%03d' % millisecond
    return '%s.%s' % (dateAndTime, millisecondText)

def printWithTimestamp(inputStream):
    while True:
        line = inputStream.readline()
        if len(line) == 0:
            break

        timestamp = time()
        print timestamp + ' ' + line,

def main():
    if len(sys.argv) == 1:
        printWithTimestamp(sys.stdin)
    else:
        import subprocess
        p = subprocess.Popen(sys.argv[1:], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
        printWithTimestamp(p.stdout)
        returncode = p.wait()
        sys.exit(returncode)

if __name__ == '__main__':
    main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment