Skip to content

Instantly share code, notes, and snippets.

@MikeDacre
Created August 22, 2014 23:36
Show Gist options
  • Save MikeDacre/72edb116b5996aef9feb to your computer and use it in GitHub Desktop.
Save MikeDacre/72edb116b5996aef9feb to your computer and use it in GitHub Desktop.
Little logging script to make writing timed messages easier
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# vim:fenc=utf-8 tabstop=4 expandtab shiftwidth=4 softtabstop=4
"""
#====================================================================================
#
# FILE: logme (python 3)
# AUTHOR: Michael D Dacre, [email protected]
# ORGANIZATION: Stanford University
# LICENSE: Open Source - Public - Do as you wish (no license) - Mike Dacre
# VERSION: 1
# CREATED: 2013-08-26 10:39
# Last modified: 2014-01-30 17:36
#
# DESCRIPTION: Simple logging functions for timed messages in python
#
# USAGE: Import and use as a module
#
#====================================================================================
"""
import sys
def open_log(logfile=''):
""" Take either a string or a filehandle, detect if string.
If string, open as file in append mode.
If file, get name, close file, and reopen in append mode
Return resulting file"""
if logfile:
if isinstance(logfile, str):
finalfile = open(logfile, 'a')
elif getattr(logfile, 'name') == '<stderr>' or getattr(logfile, 'name') == '<stdout>':
finalfile = logfile
elif not getattr(logfile, 'mode') == 'a':
logfile.close()
finalfile = open(logfile, 'a')
else:
raise Exception("logfile is not valid")
else:
finalfile = sys.stderr
return finalfile
def logme(output, logfile='', print_level=0):
"""Print a string to logfile"""
import datetime
timestamp = datetime.datetime.now().strftime("%Y%m%d %H:%M:%S")
output = str(output)
timeput = ' | '.join([timestamp, output])
stderr = False
stdout = False
if logfile:
if isinstance(logfile, str):
with open(logfile, 'a') as outfile:
print(timeput, file=outfile)
elif getattr(logfile, 'name') == '<stderr>':
print(timeput, file=logfile)
stderr = True
elif getattr(logfile, 'name') == '<stdout>':
print(timeput, file=logfile)
stdout = True
elif getattr(logfile, 'mode') == 'a':
if getattr(logfile, 'closed'):
with open(logfile.name, 'a') as outfile:
print(timeput, file=outfile)
else:
print(timeput, file=logfile)
else:
logfile.close()
with open(logfile, 'a') as outfile:
print(timeput, file=outfile)
else:
print(timeput, file=sys.stderr)
stderr = True
if print_level == 1 and not stdout:
print(output)
elif print_level == 2 and not stderr:
print(output, file=sys.stderr)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment