Created
October 21, 2016 14:40
-
-
Save benauthor/920777f0d2f3e2915bfbed0404339ede to your computer and use it in GitHub Desktop.
statsd logger sketch
This file contains hidden or 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 logging | |
import os | |
from logging.handlers import DatagramHandler | |
HOST_KEY = "STATSD_HOST" | |
PORT_KEY = "STATSD_PORT" | |
logger = logging.getLogger("test") | |
class StatsdHandler(DatagramHandler): | |
def _metric(self, record): | |
return "errors.{}.{}.{}_{}".format( | |
record.name, record.levelname, record.funcName, record.lineno | |
) | |
def _prepare_increment(self, metric): | |
return "{}:1|c".format(metric) | |
def emit(self, record): | |
""" | |
Increment a statsd counter for the error that occurred. | |
""" | |
try: | |
s = self._prepare_increment(self._metric(record)) | |
self.send(s) | |
except (KeyboardInterrupt, SystemExit): | |
raise | |
except: | |
self.handleError(record) | |
logger.addHandler(StatsdHandler(os.environ[HOST_KEY], int(os.environ[PORT_KEY]))) | |
def main(): | |
try: | |
raise Exception("wow") | |
except Exception as e: | |
logger.error(e) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Adding
lineno
to the stat name will increase the cardinality a lot -- any edit to the source file might result in a new error. Therefore I wouldn't includelineno
.