Skip to content

Instantly share code, notes, and snippets.

@kbrgl
Last active June 20, 2020 16:17
Show Gist options
  • Save kbrgl/2d7cab03dd641ee236790390cac42d7e to your computer and use it in GitHub Desktop.
Save kbrgl/2d7cab03dd641ee236790390cac42d7e to your computer and use it in GitHub Desktop.
Zero-dependency Logger class for logging of table-structured data in Python.
class Logger:
"""Logger provides logging of table-structured data.
The first column provided must be interpretable as a title. You may provide
a 'formatting function' for each column that formats values corresponding
to that column.
>>> logger = Logger({
... 'Film Title': None,
... 'Running Time': lambda x: '{} hours'.format(round(x, 2)),
... 'Rating': lambda x: '⭐️' * x,
... }, csv=True)
Film Title,Running Time,Rating
>>> logger.log(['The Party', 5.6524, 4])
The Party,5.65 hours,⭐️⭐️⭐️⭐️
>>> logger.log(['Dracula', 2.345, 5], apply_funcs=False)
Dracula,2.345,5
"""
def __init__(self, columns, file=None, csv=False):
assert len(columns) > 0
self.file = file
self.csv = csv
self.set_columns(columns)
def set_columns(self, columns):
self.columns = list(columns.keys())
self.funcs = list(columns.values())
if self.csv:
self._log_csv(self.columns)
def set_output(self, file):
self.file = file
def _print(self, *args, **kwargs):
print(*args, **kwargs, file=self.file)
def _log_csv(self, row):
self._print(','.join(row))
def _log_pretty(self, row):
row_title = ' '.join([self.columns[0], row[0]])
self._print(row_title + '\n' + '=' * len(row_title))
for column, item in zip(self.columns[1:], row[1:]):
self._print(column + ':', item)
self._print()
def log(self, row, apply_funcs=True):
# apply user-supplied functions to current input
# and convert everything to a string for final logging
if apply_funcs:
row = [f(item) if f is not None else item
for item, f in zip(row, self.funcs)]
row = [str(item) for item in row]
# choose appropriate log function
if self.csv:
self._log_csv(row)
else:
self._log_pretty(row)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment