Created
July 25, 2018 08:05
-
-
Save svlasov/c79003f1ac55c556cd1eef94021829d8 to your computer and use it in GitHub Desktop.
stopper context manager
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import datetime | |
import logging | |
import logging.config | |
from common.util.app_context import ConfigManager | |
STOPPER_LOGGER_NAME = "stopper" | |
_sdcc_config = ConfigManager(portal={'debug': True}, | |
log={'logdir': '/var/log/sdcc', | |
'verbosity': 'DEBUG'}, | |
db={'db': 'sdcc', | |
'host': '127.0.0.1', | |
'port': 27017, | |
'user': None, | |
'password': None}, | |
master_key=None) | |
logging.config.dictConfig({ | |
'version': 1, | |
'disable_existing_loggers': False, | |
'formatters': { | |
'stopper_formatter': { | |
'format': "[%(asctime)s] [%(name)s] [runtime=%(dt)s sec] %(msg)s" | |
}, | |
}, | |
'handlers': { | |
'stopper_stream_handler': { | |
'level': 'DEBUG', | |
'class': 'logging.StreamHandler', | |
'formatter': 'stopper_formatter' | |
}, | |
'stopper_file_handler': { | |
'level': 'DEBUG', | |
'class': 'logging.handlers.WatchedFileHandler', | |
'filename': _sdcc_config['log']['logdir'] + "/stopper.log", | |
'formatter': 'stopper_formatter' | |
}, | |
}, | |
'loggers': { | |
STOPPER_LOGGER_NAME: { | |
'handlers': ['stopper_stream_handler', 'stopper_file_handler'], | |
'level': 'DEBUG', | |
'propagate': False, | |
} | |
} | |
}) | |
stopper_logger = logging.getLogger(STOPPER_LOGGER_NAME) | |
class Stopper(object): | |
def __init__(self, msg="", extra=None): | |
self.msg = msg | |
if extra is None: | |
extra = {} | |
self.extra = extra | |
def __enter__(self): | |
self.t0 = datetime.datetime.utcnow() | |
self.extra['t0'] = self.t0 | |
return self | |
def stop(self, msg=None): | |
self.t1 = datetime.datetime.utcnow() | |
self.extra['t1'] = self.t1 | |
self.dt = (self.t1 - self.t0).total_seconds() | |
self.extra['dt'] = self.dt | |
stopper_logger.debug(msg or self.msg, extra=self.extra) | |
def __exit__(self, exc_type, exc_val, exc_tb): | |
self.stop() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment