Skip to content

Instantly share code, notes, and snippets.

@soxofaan

soxofaan/timinglogger.py

Last active Aug 29, 2015
Embed
What would you like to do?
TimingLogger context manager
import datetime
import logging
class TimingLogger(object):
"""
Simple timer context manager to log the time spent in the context
to given logger (logging api).
Usage example:
with TimingLogger(title="Compile"):
# Do compile stuff here
# Result: start, end and elapsed time will be logged (to root logger in this case)
"""
def __init__(self, logger=None, title="Timer"):
self._logger = logger or logging.getLogger()
self._title = title
def __enter__(self):
self.start_time = datetime.datetime.utcnow()
self._logger.info('{title} start time: {time}'.format(title=self._title, time=self.start_time))
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.end_time = datetime.datetime.utcnow()
self.elapsed = self.end_time - self.start_time
self._logger.info('{title} end time: {time}, elapsed: {elapsed}'.format(title=self._title, time=self.end_time, elapsed=self.elapsed))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.